/*
当元素自身不具备比较性,或者具备的比较性不是所需要的。
这时,需要让容器自身具备比较性。
定义了比较器,将比较器对象作为参数传递给TreeSet集合的构造函数。
当两种排序都存在时,以比较器为主。
定义一个类,实现Comparator接口,覆盖compare方法。
*/
//TreeSet排序的第二种方式:让集合自身具备比较性。
//现在容器自身设定一个比较方法,按姓名排序。
import java.util.*;
class Print
{
public static void sop(Object obj)
{
System.out.println(obj);
}
}
class Student implements Comparable//该接口强制让学生具备比较性
{
private String name;
private int age;
Student(String name,int age)
{
this.name=name;
this.age=age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
//-----------法一:Student类实现Comparable接口,并覆盖compareTo方法。让学生具备比较性
public int compareTo(Object obj)
{
if(!(obj instanceof Student))
throw new RuntimeException("不是学生对象");
Student s = (Student)obj;
Print.sop(this.name+"...compareTo..."+s.name);
if(this.age>s.age)
return 1;
else if(this.age==s.age)
{
return this.name.compareTo(s.name);
}
return -1;
}
//---------------------------
}
//---------法二:定义容器的比较器.容器传入Comparator接口的子类,该子类再去实现Comparator接口,覆盖compare方法。让容器具备比较性。
class MyCompare implements Comparator//当两种排序都存在时,走的是比较器方法
{
public int compare(Object o1,Object o2)
{
if(!((o1 instanceof Student)&&(o2 instanceof Student)))
throw new RuntimeException("不是学生对象");
Student s1 = (Student)o1;
Student s2 = (Student)o2;
Print.sop(s1.getName()+"...compare..."+s2.getName());
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;
}
}
//---------------------
class TreeSetDemo2
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet(new MyCompare());//创建容器时,传入一个比较器
ts.add(new Student("lisi05",15));
ts.add(new Student("lisi03",19));
ts.add(new Student("lisi08",18));
ts.add(new Student("lisi03",14));
Iterator it = ts.iterator();
while(it.hasNext())
{
Object obj = it.next();
Student s = (Student)obj;
Print.sop(s.getName()+"..."+s.getAge());
}
}
}
/*
E:\javademo\day15>java TreeSetDemo2
lisi05...compare...lisi05
lisi03...compare...lisi05
lisi08...compare...lisi05
lisi03...compare...lisi05
lisi03...compare...lisi03
lisi03...14
lisi03...19
lisi05...15
lisi08...18
*/