3 回答

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超3個贊
//Written by K@stackoverflowpublic class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here ArrayList<Person> people = new ArrayList<Person>(); people.add(new Person("Subash Adhikari", 28)); people.add(new Person("K", 28)); people.add(new Person("StackOverflow", 4)); people.add(new Person("Subash Adhikari", 28)); for (int i = 0; i < people.size() - 1; i++) { for (int y = i + 1; y <= people.size() - 1; y++) { boolean check = people.get(i).equals(people.get(y)); System.out.println("-- " + people.get(i).getName() + " - VS - " + people.get(y).getName()); System.out.println(check); } } }}//written by K@stackoverflowpublic class Person { private String name; private int age; public Person(String name, int age){ this.name = name; this.age = age; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!Person.class.isAssignableFrom(obj.getClass())) { return false; } final Person other = (Person) obj; if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } if (this.age != other.age) { return false; } return true; } @Override public int hashCode() { int hash = 3; hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0); hash = 53 * hash + this.age; return hash; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; }}
產(chǎn)出:
跑:
-Subash Adhikari-VS-K false
-Subash Adhikari-VS-StackOverflow false
-Subash Adhikari-VS-Subash Adhikari True
-K-VS-StackOverflow false
-K-VS-Subash Adhikari false
-StackOverflow-VS-Subash Adhikari false
-成功構(gòu)建(總時間:0秒)

TA貢獻(xiàn)1744條經(jīng)驗(yàn) 獲得超4個贊
equals
age

TA貢獻(xiàn)1963條經(jīng)驗(yàn) 獲得超6個贊
記得重寫 hashCode()
也是 這個 equals
方法應(yīng)該有 Object
,不是 People
作為它的參數(shù)類型。目前,您正在重載,而不是重寫相等方法,這可能不是您想要的,特別是考慮到稍后檢查它的類型。 你可以用 instanceof
檢查它是一個人的對象。 if (!(other instanceof People)) { result = false;}
equals
用于所有對象,但不用于原語。我覺得你的平均年齡是 int
(原語),在這種情況下,只需使用 ==
..請注意,Integer(帶有大寫“i”)是一個對象,應(yīng)該將其與等于進(jìn)行比較。
添加回答
舉報