TreeSet集合排序有两种方式,Comparable和Comparator区别:a、让元素自身具备比较性,需要元素对象实现Comparable接口,覆盖compareTo方法;
b、让集合自身具备比较性,需要定义一个实现了Comparator接口的比较器,并覆盖compare方法,并将该类对象作为实际参数传递给TreeSet集合的构造函数;第二种方式较为灵活。,对Set集合中的元素进行排序,底层数据结构是二叉树,当两种排序都存在时,以比较器排序为主;
- class TreeSetTest
- {
- public static void main(String[] args)
- {
- TreeSet ts = new TreeSet(new StrLenComparator());//创建一个TreeSet,并传入一个比较器
- ts.add("abcd");//添加元素
- ts.add("cc");
- ts.add("cba");
- ts.add("aaa");
- ts.add("z");
- ts.add("hahaha");
- Iterator it = ts.iterator();//遍历打印这个集合,查看排序结果
- while(it.hasNext())
- {
- System.out.println(it.next());
- }
- }
- }
- class StrLenComparator implements Comparator
- {
- public int compare(Object o1,Object o2)//覆盖compare方法
- {
- String s1 = (String)o1;
- String s2 = (String)o2;
-
- int num = new Integer(s1.length()).compareTo(new Integer(s2.length()));//字符串按长度从短到长排序
- if(num==0)
- return s1.compareTo(s2);
- return num;
- }
- }
复制代码 当元素自身不具备比较性,或者具备的比较性不是所需要的,这时需要让容器自身具备比较性;定义了比较器,将比较器对象作为参数传递给TreeSet集合的构造函数;当两种排序都存在时,以比较器为主。
定义一个类,实现Comparator接口,覆盖compare方法:
- 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;
- if(this.age>s.age)
- return 1;
- if(this.age==s.age)
- 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();
- ts.add(new Student("lisi02",22));
- ts.add(new Student("lisi02",21));
- ts.add(new Student("lisi007",20));
- ts.add(new Student("lisi09",19));
- ts.add(new Student("lisi06",18));
- ts.add(new Student("lisi06",18));
- ts.add(new Student("lisi007",29));
- //ts.add(new Student("lisi007",20));
- //ts.add(new Student("lisi01",40));
- Iterator it = ts.iterator();
- while(it.hasNext())
- {
- Student stu = (Student)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)
- return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
- return num;
- }
- }
复制代码
|