日期:2014-05-20 浏览次数:20903 次
class A { private String name; private String idstr; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIdstr() { return idstr; } public void setIdstr(String idstr) { this.idstr = idstr; } public A() { } A(String name, String idstr) { this.name = name; this.idstr = idstr; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj != null && (obj instanceof A)) { A AObj = (A) obj; System.out.println(AObj.idstr); if ((this.idstr).equals(AObj.idstr)) { return true; } } return false; } } public class B { public static void main(String[] args) { A p1 = new A("孙悟空", "shanghai"); A p2 = new A("孙行者", "xi'an"); A p3 = new A("孙悟饭", "shanghai"); System.out.println("p1,p2是否相等:" + p1.equals(p2)); System.out.println("p2,p3是否相等:" + p2.equals(p3)); System.out.println("p2,p3是否相等:" + p1.equals(p3)); } }
------解决方案--------------------
class A { private String name; private String idstr; public A(String name){ this.name = name; } A(String name, String idstr) { this.name = name; this.idstr = idstr; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj != null && obj instanceof A) { A a = (A)obj; if (this.getName().equals(a.getName())){ return true; } } return false; } public String getIdstr() { return idstr; } public void setIdstr(String idstr) { this.idstr = idstr; } public String getName() { return name; } public void setName(String name) { this.name = name; } } class Person1 extends A{ public Person1(String name) { super(name); } } public class B { public static void main(String[] args) { A p1 = new A("孙悟空"); A p2 = new Person1("孙悟空"); A p3 = new A("孙悟饭"); System.out.println("p1,p2是否相等:" + p1.equals(p2)); System.out.println("p2,p3是否相等:" + p2.equals(p3)); } } //楼主好好打基础,基础不行,写代码会很累的。