import java.util.*;
class Collection
{
public static void main(String[] args)
{
TreeSet hs = new TreeSet(new mycomparetor());//传入比较器
hs.add(new person("java05",25));
hs.add(new person("java03",23));
hs.add(new person("java08",21));
hs.add(new person("java07",24));
Iterator it = hs.iterator();
while(it.hasNext())
{
person p = (person)it.next();
System.out.println(p.getname()+"::"+p.getage());
}
}
}
class person implements Comparable
{
String name;
int age;
person(String name,int age)
{
this.age=age;
this.name=name;
}
public String getname()
{
return name;
}
public int getage()
{
return age;
}
//复写hashCode()方法
public int hashCode()
{
return name.hashCode()+age*3;
}
//复写equals方法
public boolean equals(Object obj)
{
if(!(obj instanceof person))
throw new ClassCastException("类型错误");
person p = (person)obj;
if(this.age>p.age)
return true;
if(this.age==p.age)
{
return this.name.equals(p.name);
}
return false;
}
//复写compareTo()方法
public int compareTo(Object obj)
{
if(!(obj instanceof person))
throw new ClassCastException("类型错误");
person p = (person)obj;
int num = this.age-p.age ;
if(num>0)
return 1;
if(num==0)
{
return this.name.compareTo(p.name);
}
return -1;
}
}
//自定义比较器
class mycomparetor implements Comparator<person>
{
public int compare(person p1,person p2)
{
int num = p1.getname().compareTo(p2.getname());
if(num==0)
return new Integer(p1.getage()).compareTo(new Integer(p2.getage()));
return num;
}
}
/*
1.HashSet,HashMap集合通过复写hashCode()与equals()方法来控制元素的唯一性
2.TreeSet,TreeMap集合通过复写实现Comparable接口,复写compareTo()方法来控制元素的唯一性
3.自定义比较器通过实现Comparator接口,复写compare()方法
*/ |
|