import java.util.*;
class Text2_HashSet_and_TreeSet {
public static void main(String[] args){
HashSet has = new HashSet();
has.add(new Person("张三",23));
has.add(new Person("李四",24));
has.add(new Person("王五",25));
has.add(new Person("赵六",26));
Iterator it = has.iterator();
while(it.hasNext()) {
Person e = (Person) it.next();
System.out.println(e.getName()+"..."+e.getAge());
}
System.out.println("------------------------------");
TreeSet tree = new TreeSet();
tree.add(new Person("张三",23));
tree.add(new Person("李四",24));
tree.add(new Person("王五",25));
tree.add(new Person("赵六",26));
Iterator itt = tree.iterator();
while(itt.hasNext()) {
Person e = (Person) itt.next();
System.out.println(e.getName()+"..."+e.getAge());
}
}
}
class Person implements Comparable{
private String name;
private int age;
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setAge (int age){
this.age = age;
}
public int getAge(){
return age;
}
public Person(String name,int age){
this.name = name;
this.age = age;
}
public int hashCode(){
return name.hashCode()+age;
}
public boolean equals(Object obj){
if (!(obj instanceof Person)) {
throw new RuntimeException();
}
Person p = (Person) obj;
return this.getName().equals(p.getName()) & new Integer(this.getAge()).equals(new Integer(p.getAge()));
}
public int compareTo(Object obj){
if (!(obj instanceof Person)){
throw new RuntimeException("非人类!");
}
Person p = (Person) obj;
int y = this.getName().compareTo(p.getName());
if (y == 0) {
return new Integer(this.getAge()).compareTo(new Integer(p.getAge()));
}
return y;
}
}
|