TreeSet
TreeSet可以对set集合中的元素进行排序,默认按照asic码表的自然顺序排序,之所以treeset能排序是因为底层是二叉树,数据越多越慢,TreeSet是依靠TreeMap来实现的
像TreeSet中存储自定义对象需要实现comparable接口。

 package com.iotek.set;

 import java.util.Iterator;
import java.util.TreeSet; public class TreeSetDemo1 { public static void main(String[] args) { TreeSet<Personb> pset = new TreeSet<Personb>();
pset.add(new Personb("chenchen", 30));
pset.add(new Personb("lisi", 20));
pset.add(new Personb("wangwu", 10));
pset.add(new Personb("rose", 40));
pset.add(new Personb("rose", 41));
System.out.println(pset);
Iterator<Personb> it = pset.iterator(); //
while (it.hasNext()) { // 判断容器中有没有被迭代的数据
Personb p = it.next(); // 取出来的是个Person类型
System.out.println(p.getName() + "--" + p.getAge());
} /*
* 调用TreeSet类的对象pset的iterator()方法,返回一个迭代器对象, 使用这个迭代器对象
*/ /*
* (1)当Person类不实现Comparable接口时,System.out.println(pset)这条语句会报错:
* Exception in thread "main"java.lang.ClassCastException:
* com.iotek.set.Person cannot be cast to java.lang.Comparable
* 这是因为,TreeSet和TreeMap一样,都是按照键的自然顺序来升序排列,
* 对象无法做自然升序排列,应该要告诉TreeSet按照什么规则来排序
* (2)如何对TreeSet对象的add()方法中添加的对象进行排序?需要这个对象的类
* 来实现Comparable接口,在接口中重写compareTo()方法,来声明比比较规则
*/
} } /*
* 当调用TreeSet的无参数构造方法,其内部创建了一个TreeMap对象 public TreeSet() { this(new
* TreeMap<E,Object>()); }
*/
class Personb implements Comparable<Personb> {
private String name;
private int age; public Personb(String name, int age) {
super();
this.name = name;
this.age = age;
// this.age是Person类的实例化对象的age
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} @Override
public int compareTo(Personb o) {
if (this.age - o.getAge() > 0) {
return 1;
} else if (this.age - o.getAge() < 0) {
return -1;
}
return 0;
} @Override
public String toString() {
return "Personb [name=" + name + ", age=" + age + "]";
} }

ht-7  treeSet特性-LMLPHP

TreeSet及常用API
(1)TreeSet为使用树来进行存储的Set接口提供了一个工具,对象按升序存储,访问和检索很快
(2)在存储了大量的需要进行快速检索的排序信息的情况下,TreeSet是一个很好的选择
(3)构造方法
TreeSet()
TreeSet(Collection c)
TreeSet(Comparator comp)
TreeSet(SortedSet ss)

(4)总结 :TreeSet的内部操作的底层数据是TreeMap,只是我们操作的是TreeMap的Key
TreeMap的Key是默认按照自然顺序升序排列的

05-11 20:44