import java.util.*;
class Student implements Comparable//所以学生就要实现接口比较方法,该接口强制让它具有比较性。
{
private String name;
private int age;
Student(String name,int age)
{
this.name=name;
this.age=age;
}
public int compareTo(Object obj)
{
if (!(obj instanceof Student))
throw new RuntimeException("不是学生对象");
Student s=(Student)obj;
//System.out.println(this.name+"....coparable...."+s.name);
if (this.age>s.age)
return 1;
if (this.age==s.age)//当姓名不相同 而年龄相同了,是不是一个人啊,所以要判断姓名再String中有comparaTo功能,按字典排序
{
return this.name.compareTo(s.name);
}
return -1;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
class TreeSetDemo2
{
public static void main(String[] args)
{
//TreeSet ts = new TreeSet();//第一种进行元素排序了 往TreeSet里存数据必须数据要有比较性
??? TreeSet ts = new TreeSet(new MyCompare());//第二种方法,这个地方传人的 MyCompare怎么理解啊,拆开写怎么写啊?糊涂了
ts.add(new Student("lisi01",28));
ts.add(new Student("lisi02",25));
ts.add(new Student("lisi03",19));
ts.add(new Student("zhangsan",19));
Iterator it = ts.iterator();
while (it.hasNext())
{
Student stu=(Student)it.next();// 强转调用特有方法
//System.out.println(it.next());//打印的是对象
System.out.println(stu.getName()+"..."+stu.getAge());
}
}
}
class MyCompare implements Comparator//类要实现这个接口
{
public int compare(Object o1,Object o2)
{
Student s1=(Student)o1;
Student s2=(Student)o2;
int num=s1.getName().compareTo(s2.getName());//比较字符串
if (num==0)
{
if(s1.getAge()>s2.getAge())
return 1;
if(s1.getAge()== s2.getAge())
return 0;
return -1;
}
return num;
}
} |