方法一:元素实现Comparable接口,重写compareTo()方法,实现集合排序
方法二:定义一个比较器传给TreeSet的构造函数,该比较器实现Comparator接口,重写compare()方法,实现集合排序- import java.util.TreeSet;
- import java.util.Iterator;
- import java.util.Comparator;
- /**
- 1.实现Comparable接口,重写compareTo()方法,实现集合排序
- */
- class Student implements Comparable
- {
- String name;
- 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 o = (Student)obj;
- if(this.age==o.age)
- return this.name.compareTo(o.name);
- else if(this.age>o.age)
- return 1;
- else
- return -1;
- }
- public String toString()
- {
- return this.name+"-"+this.age;
- }
- }
- class Test
- {
- public static void main(String[] args)
- {
- TreeSet<Student> ts = new TreeSet<Student>();
- ts.add(new Student("John",20));
- ts.add(new Student("Jack",20));
- ts.add(new Student("Jam",21));
-
- Iterator<Student>it = ts.iterator();
- while(it.hasNext())
- {
- System.out.println(it.next());
- }
-
- /**
- 2.(匿名内部类的方式)实现Comparator接口,重写compare()方法,实现集合排序
- */
- TreeSet<Student> ts2 = new TreeSet<Student>(
- new Comparator<Student>()
- {
- public int compare(Student sa, Student sb)
- {
- if(sa.age==sb.age)
- return sa.name.compareTo(sb.name);
- else if(sa.age>sb.age)
- return 1;
- else
- return -1;
- }
- }
- );
-
- ts2.add(new Student("John",20));
- ts2.add(new Student("Jack",20));
- ts2.add(new Student("Jam",21));
- System.out.println();
-
- Iterator<Student>it2 = ts2.iterator();
- while(it2.hasNext())
- {
- System.out.println(it2.next());
- }
- }
- }
复制代码 测试结果:- Jack-20
- John-20
- Jam-21
- Jack-20
- John-20
- Jam-21
复制代码 |