import java.util.*;
/*
当元素自身不具有比较性时,或者是具有的比较性不是所需要的。
这是就让容器具备比较性。
定义了比较器,将比较器对象作为参数传递给TreeSet集合的构造函数。
当两种排序都存在时,以比较器为主。
定义一个类,实现Comparator接口,覆盖compare方法。
*/
class Teacher
{
private String name;
private int age;
public static void sop(Object obj)
{
System.out.println(obj);
}
Teacher(String name,int age)
{
this.name = name;
this.age = age;
}
}
class Student implements Comparable//该接口强制学生具有比较性
{
private String name;
private int age;
public static void sop(Object obj)
{
System.out.println(obj);
}
Student(String name,int age)
{
this.name = name;
this.age = age;
}
public int compareTo(Object obj)
{
//当返回值为0时,之存入一个元素。
//return 0;
//按存入的逆序输出
//return -1;
//怎么存入怎么输出
//return 1;
if(!(obj instanceof Student))
throw new RuntimeException("不是学生");
Student s = (Student)obj;
//sop(this.getName()+"....compareTo..."+s.getName());
if(this.age>s.age)
return 1;
if(this.age==s.age)
return this.name.compareTo(s.name);
return -1;
}
// public void setName(String name )
// {
// this.name = name;
// }
// public void setAge(int age)
// {
// this.age = age;
// }
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
class TreeSetDemo2
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet(/*new MyCompare()*/);
//ts.add(new Teacher("xiaoli00",28));
ts.add(new Student("xiaoli02",22));
ts.add(new Student("xiaoli02",23));
ts.add(new Student("xiaoli03",24));
ts.add(new Student("xiaoli03",25));
ts.add(new Student("xiaoli01",20));
Iterator it = ts.iterator();
while(it.hasNext())
{
Student stu =(Student)it.next();
sop(stu.getName()+"----"+stu.getAge());
}
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
class MyCompare implements Comparator
{
public int compare(Object o1,Object o2)
{
Student s1 = (Student)o1;
Student s2 = (Student)o2;
int name = (s1.getName()).compareTo(s2.getName());
if (name==0)
{
return new Integer(s1.getAge()).compareTo(s2.getAge());
/*if (s1.getAge()>s2.getAge())
return 1;
if(s1.getAge()<s2.getAge())
return -1;
return 0;*/
}
return name;
}
}
TreeSet2
最新推荐文章于 2022-07-26 17:48:47 发布