TreeSet的使用方法和注意事项

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,有助于理解=====================

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值