TreeSet的使用方法和注意事项

来源:互联网 发布:py是什么意思网络语言 编辑:程序博客网 时间:2024/05/02 06:09
Set的子接口SortedSet,TreeSet实现了SortedSet。
TreeSet是无序的。

    a)

public static void main(String[] args) {                TreeSet  set = new TreeSet();                set.add("A");        set.add("B");        set.add("C");        set.add("D");        set.add("E");        set.add("F");                        System.out.println(set);    }}


 

有程序可知,TreeSet可以自动把有序的序列排序。(对于一些无序的对象以及自定义的对象是无法自动排序的。同时会抛出ClassCastException异常,解决方法看下面的例子)

b)

public class TestTreeSet {     public static void main(String[] args) {                TreeSet  set = new TreeSet(new MyCompare());                set.add("A");        set.add("B");        set.add("C");        set.add("D");        set.add("E");        set.add("F");                        System.out.println(set);    }}  class MyCompare implements Comparator{        @Override    publicint compare(Object o1,Object o2) {        Strings1 = (String)o1;        Strings2 = (String)o2;                return s2.compareTo(s1);        //return -s1.compareTo(s2);    }}


 

TressSet通过构造方法TreeSet(Comparator<?superE>comparator)指定比较器。

如果想把数据逆序,可直接在compare方法中实现,上述代码既是实现字符的逆序。

C)关于对象的比较

 public class TestTreeSet1 {     public static void main(String[] args) {                TreeSet set = new TreeSet(new MyCompare());                 People p2 = new People(20);        People p3 = new People(10);        People p4 = new People(30);        People p1 =new People(40);                set.add(p1);        set.add(p2);        set.add(p3);        set.add(p4);                for(Iterator it =set.iterator(); it.hasNext();){            Peoplep = (People)it.next();            System.out.println(p.score);        }    }}  class People{     int score;     People(int score){        this.score = score;    } } class MyCompare implements Comparator{     @Override    publicint compare(Object o1,Object o2) {        People p1 = (People)o1;        People p2 = (People)o2;                return p1.score - p2.score;    }    }


 

 

====================个人建议:分析代码时,请参考API,有助于理解=====================

原创粉丝点击