标签:
1 import java.util.*; 2 3 public class BasicContainer { 4 public static void main(String[] args) { 5 Collection c = new HashSet(); 6 c.add("hello"); 7 c.add(new Name("f1","l1")); 8 c.add(new Integer(100)); 9 c.remove("hello"); 10 c.remove(new Integer(100)); 11 System.out.println 12 (c.remove(new Name("f1","l1"))); 13 System.out.println(c); 14 } 15 16 17 } 18 19 class Name implements Comparable { 20 private String firstName,lastName; 21 public Name(String firstName, String lastName) { 22 this.firstName = firstName; this.lastName = lastName; 23 } 24 public String getFirstName() { return firstName; } 25 public String getLastName() { return lastName; } 26 public String toString() { return firstName + " " + lastName; } 27 28 public boolean equals(Object obj) { 29 if (obj instanceof Name) { 30 Name name = (Name) obj; 31 return (firstName.equals(name.firstName)) 32 && (lastName.equals(name.lastName)); 33 } 34 return super.equals(obj); 35 } 36 public int hashCode() { 37 return firstName.hashCode(); 38 } 39 40 41 42 public int compareTo(Object o) { 43 Name n = (Name)o; 44 int lastCmp = 45 lastName.compareTo(n.lastName); 46 return 47 (lastCmp!=0 ? lastCmp : 48 firstName.compareTo(n.firstName)); 49 } 50 51 }
标签:
原文地址:http://www.cnblogs.com/roger-h/p/4480641.html