import java.util.*;
/*
需求:往TreeSet集合中存储一个自定义的学生类,以学生的姓名进行排序
*/
class Person implements Comparable
{
private String name;
private int age;
Person(String name,int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public int compareTo(Object obj)
{
Person p = (Person)obj;
int num;
num = this.name.compareTo(p.name); // hashCode() -- 返回int类型
if (num==0)
{
if(this.age>p.age)
return 1;
if(this.age==p.age)
return 0;
return -1;
}
return num;
}
}
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet();
ts.add(new Person("java01",21));
ts.add(new Person("java02",22));
ts.add(new Person("java02",21));
ts.add(new Person("java03",21));
Iterator it = ts.iterator();
while (it.hasNext())
{
Person p = (Person)it.next();
System.out.println(p.getName()+"::"+p.getAge());
}
}
}
|
|