日期:2014-05-20 浏览次数:20700 次
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
class Person2 implements Comparable{
private int id;
private String name;
private int age;
public Person2(){
}
public Person2(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public boolean equals(Object o){
Person2 p1 = (Person2)o;
return id==p1.id&&age==p1.age && name.equals(p1.name);
}
public String toString(){
return id+"--"+ name+"--"+ age;
}
public int hashCode(){
return id*age*name.hashCode();
}
@Override
public int compareTo(Object o) {
Person2 p = (Person2)o;
if(this.id>p.id){
return 1;
}else if(this.id<p.id){
return -1;
}else{
return 0;
}
}
}
public class TestHashSet {
public static void main(String[] args) {
Set set = new HashSet();
set.add(new Person2(1,"zhangshan",15));
set.add(new Person2(1,"zhangshan",15));
set.add(new Person2(2,"lisi",15));
set.add(new Person2(3,"li",35));
for(Iterator it=set.iterator();it.hasNext();){
System.out.println(it.next());
}
}
}
输出结果是:、
2--lisi--15
1--zhangshan--15
3--li--35