标签:
1 import java.util.*; 2 3 public class Test { 4 public static void main(String[] args) { 5 Collection c = new HashSet(); 6 c.add("hello"); 7 c.add(new Name("lovy", "winsy")); 8 c.add(new Integer(100)); 9 c.remove("hello"); 10 c.remove(new Integer(100)); 11 c.remove(new Name("lovy", "winsy")); 12 System.out.println(c.size()); 13 System.out.print(c); 14 } 15 } 16 17 class Name { 18 private String firstName; 19 private String lastName; 20 21 public Name(String firstName, String lastName) { 22 this.firstName = firstName; 23 this.lastName = lastName; 24 } 25 26 public String getFirstName() { 27 return firstName; 28 } 29 30 public String getLastName() { 31 return lastName; 32 } 33 34 public String toString() { 35 return firstName + " " + lastName; 36 } 37 38 /* public boolean equals(Object obj) { 39 if (obj instanceof Name) { 40 Name name = (Name) obj; 41 return (firstName.equals(name.firstName)) 42 && (lastName.equals(name.lastName)); 43 } 44 return super.equals(obj); 45 } 46 47 public int hashCode() { 48 return firstName.hashCode(); 49 }*/ 50 }
结果如下
1
[lovy winsy]
总结
Collection的remove()默认依据Object的equals(),Object的equals()其实是比较引用所指是否为同一对象,由于Integer和String类重写了equals(),比较的是两引用所指对象内容是否相同,因此"hello"和100都被顺利删除了
Name仍然继承Object的equals(),因此需要重写Name的equals()方法,才能成功删除。
重写equals(),即注释部分之后,结果如下
0
[]
一个Collection中重写equals()和hashCode()的例子
标签:
原文地址:http://www.cnblogs.com/lovywinsy/p/4383563.html