Set容器——TreeSet及常用API

TreeSet及常用Api

①   TreeSet为使用树来进行存储的Set接口提供了一个工具,对象按升序存储,访问和检索很快;

②   在存储了大量的需要进行快速检索的排序信息的情况下,TreeSet是一个很好的选择;

③   构造方法:

a)   TreeSet();

b)   TreeSet(Collection c)

c)    TreeSet(Comparator comp)

d)    TreeSet(SortedSet ss)

总结:TreeSet的内部操作的底层数据是TreeMap,只是我们操作的是TreeMap的key;

创建一个Person类:

 1 class Person{
 2     private String name;
 3     private int age;
 4     public Person(String name, int age) {
 5         super();
 6         this.name = name;
 7         this.age = age;
 8     }
 9     public String getName() {
10         return name;
11     }
12     public void setName(String name) {
13         this.name = name;
14     }
15     public int getAge() {
16         return age;
17     }
18     public void setAge(int age) {
19         this.age = age;
20     }
21 }

主方法中创建实例,添加元素,输出:

1         TreeSet<Person> pset=new TreeSet<Person>();
2         pset.add(new Person("张三",20));
3         pset.add(new Person("李四",30));
4         pset.add(new Person("王五",40));
5         pset.add(new Person("小明",50));
6         System.out.println(pset);

输出结果:

报错,与TreeMap相同没有比较方法

解决方法与TreeMap中的一样,

方法一:实现Comparable接口的方法

 1 class Person implements Comparable<Person>{ 2 } 

重构方法如下

1     @Override
2     public int compareTo(Person o) {
3         if (this.age - o.getAge() > 0) {
4             return 1;
5         } else if (this.age - o.getAge() < 0) {
6             return -1;
7         }
8         return 0;
9     }

再在主方法中使用迭代器输出TreeMap中的值

1         Iterator<Person> it = pset.iterator();
2         while(it.hasNext()){
3             Person p=it.next();
4             System.out.println(p.getName()+"--"+p.getAge());
5         }

输出结果:

张三--20

李四--30

王五--40

小明—50

 

方法二:使用匿名内部类

 1     TreeSet<Person> pset = new TreeSet<Person>(new Comparator<Person>() {
 2 
 3             @Override
 4             public int compare(Person o1, Person o2) {
 5                 if(o1.getAge()>o2.getAge()){
 6                     return 1;
 7                 }
 8                 else if(o1.getAge()<o2.getAge()){
 9                     return -1;
10                 }
11                 return 0;
12             }
13         });

输出结果与上面相同

原文地址:https://www.cnblogs.com/wzy330782/p/5402639.html