您的位置:首页 > 其它

36、TreeSet详解

2016-05-28 20:31 204 查看
  TreeSet是SortedSet接口的实现类,TreeSet可以保证元素处于排序状态。与HashSet相比,TreeSet还提供了如下几个而外的方法:

  1)、Comparator comparator():如果TreeSet采用了定制排序,则方法返回定制排序所使用的Comparator;如果TreeSet采用的是自然排序,则返回null

  2)、Object first():返回集合的第一个元素

  3)、Object last():返回集合的最后一个元素

  4)、Object lower(Object e):返回集合中位于指定元素之前的元素

  5)、Object higher(Object e):返回集合中位于指定元素之后的元素

  6)、SortedSet subSet(Object fromElement,Object toElement):返回此Set的子集合,返回从fromElement(包含)到toElement(不包含)

  7)、SortedSet headSet(Object toElement):返回此Set的子集,由小于toElement的元素组成

  8)、SortedSet tailSet(Object fromElement):返回此Set的子集,由大于或等于fromElement的元素组成

  由于TreeSet元素有排序状态,TreeSet会调用集合元素的compareTo方法来比较元素之间的大小,所以这些元素对于的类必须实现Comparable接口。同时在元素调用compareTo方法时,如果两个元素的类型不一致,会出现ClassCastException异常。

  总结起来,TreeSet使用要求有:

  1、TreeSet中存储的对象必须是同类型的对象

  2、TreeSet中存储的类型必须实现了Comparable接口

  

public class Test {

public static void main(String[] args) {
Student s1=new Student("robin", 20080101);
Student s2=new Student("ken", 20080114);
Student s3=new Student("lucy", 20080102);
Student s4=new Student("jock", 20080103);
TreeSet<Student> set=new TreeSet<Student>();

set.add(s1);
set.add(s2);
set.add(s3);
set.add(s4);
System.out.println(set);

}
}

class Student implements Comparable<Student>{
private String name;
private int code;
public int getCode(){
return code;
}
public Student(String name,int code){
this.name=name;
this.code=code;
}
@Override
public int compareTo(Student o) {
return this.code-o.code;
}
@Override
public String toString() {
return "Student [name=" + name + ", code=" + code + "]";
}

}


  结果:[Student [name=robin, code=20080101], Student [name=lucy, code=20080102], Student [name=jock, code=20080103], Student [name=ken, code=20080114]]

  如果改变TreeSet中对象的实例变量,这将导致它与其它对象的大小顺序发生变化,但TreeSet不会再次调整他们的顺序,然后会出现其它问题。所以在使用TreeSet和HashSet时,为了程序的更加健壮,推荐不要修改放入HashSet和TreeSet中的元素的关键实例变量。

定制排序

public static void main(String[] args) {
Student s1=new Student("robin", 20080101);
Student s2=new Student("ken", 20080114);
Student s3=new Student("lucy", 20080102);
Student s4=new Student("jock", 20080103);
TreeSet<Student> set=new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return o2.getCode()-o1.getCode();
}
});

set.add(s1);
set.add(s2);
set.add(s3);
set.add(s4);
System.out.println(set);

}


输出结果:[Student [name=ken, code=20080114], Student [name=jock, code=20080103], Student [name=lucy, code=20080102], Student [name=robin, code=20080101]]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: