標籤:
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()的例子