import java.util.*;
/*想要对人对象按照年龄进行从小到大的排序,
treeset集合是用于给元素进行排序的
那么自定义元素本身不具备比较性,treeset集合是无法对元素进行排序的
所以在自定义对象时,需要对象具备一个扩展功能,用于比较,而java已经提供了接口,
让实现它的对象具备比较性,那么自定义类要想被treeset排序,就必须实现comparable接口
以具备比较功能。
*/
/*treeset集合可以对set集合中的元素进行排序,它的数据结构是二叉树,这种数据结构可以提高排序性能
那么treeset集合是怎样保证元素的唯一性呢?
是根据比较方法的返回值来确定的,只要返回的值是0,就代表元素重复*/
//比较的时候要注意主要条件和次要条件,如果主要条件相同,一定要比较次要条件。
public class TreeSetDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeSet ts=new TreeSet();
ts.add(new Person("lisi3",20));
ts.add(new Person("lisi4",21));
ts.add(new Person("lisi6",29));
ts.add(new Person("lisi9",23));
ts.add(new Person("lisi1",20));
Iterator it=ts.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
class Person implements Comparable
{
String name;
int age;
Person(String name,int age)
{
this.name=name;
this.age=age;
}
public int compareTo(Object obj)
{
Person p=(Person)obj;
//int num=this.age-p.age;
int num=new Integer(this.age).compareTo(new Integer(p.age));
return num==0? this.name.compareTo(p.name):num;
/*if(this.age>p.age)
return 1;
else if(this.age
return -1;
else
return 0;*/
}
public int hashCode()
{
//System.out.println(this+".....hashCode");
final int NUMBER=39;
return name.hashCode()+age*NUMBER;
}/**/
public boolean equals(Object obj)
{
//System.out.println(this+"....equals...."+obj);
if(this==obj)
return true;
if(!(obj instanceof Person))
return false;
Person p=(Person)obj;
return this.name.equals(p.name) && this.age==p.age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name+"::"+age;
}
}
run :
lisi1::20
lisi3::20
lisi4::21
lisi9::23
lisi6::29