TreeSet中實現自己的Comparator,以及常見的Collections方法的使用

比起之前所說的HashSet,TreeSet又有了一定的優勢,TreeSet是SortedSet中的子類,顧名思義這是有序的一個集合,先看一個例子:

   public class TreeSetTest
{
    public static void main(String[] args)
    {
        TreeSet tree = new TreeSet();
        tree.add("aa");
        tree.add("ad");
        tree.add("c");
        tree.add("b");
        tree.add("e");
        System.out.println(tree);
    }

}

如果這是一個,ArrayList或者是Linkedlist他會是原樣輸出,如果是一個HashSet,他會亂序輸出,但現在他會按順序輸出。

     但是如果add方法中是一個自己定義的類對象:

public class TreeSetTest
{
    public static void main(String[] args)
    {
        TreeSet tree= new TreeSet();
        tree.add(new Persion("zhangran"));
        tree.add(new Persion("zhang"));
        System.out.println(tree);
        
    }
}
class Persion
{
    String name;
    Persion(String name)
    {
        this.name = name;
        
    }
    public String toString()
    {
        return this.name;
    }
}

此時此時便會出現異常,問題在於,TreeSet本來是應該比較大小,然後按順序輸出的但是,但是現在你給了他一個自己定義的類,它便無法識別,不知道怎麼排序了,所以你現在所做的就是告訴他如何排序,此時就需要一個比較器(Comparator):

public class TreeSetTest
{
    public static void main(String[] args)
    {

        TreeSet tree= new TreeSet(new MyComparator());
        tree.add(new Persion("zhangran"));
        tree.add(new Persion("zhang"));
        System.out.println(tree);
        
    }
}

class Persion
{
    String name;
    Persion(String name)
    {
        this.name = name;
        
    }
    public    String toString()
    {
        return this.name;
    }
}
class MyComparator implements Comparator
{

    @Override
    public int compare(Object o1, Object o2)
    {
        Persion p1 = (Persion)o1;
        Persion p2 = (Persion)o2;
        return p1.name.compareTo(p2.name);
    }
    
}
這樣TreeSet便會知道你是要按照字符串從小到大排序,這樣便可以順利運行。


下面再講一下Collections中的某些方法,Collections是集合的父類,裏面有許多的靜態方法,可以給他的子類對象提供許多功能

1.讓LinkedList中的數值有序輸出

LinkedList list = new LinkedList();

list.add(new Integer(1));

list.add(new Integer(0));

list.add(new Integer(3));

list.add(new Integer(2));

//生成一個比較器

Comparator com = Collections.reverseOrder();//倒敘

Collections.sort(list,com);//list按照com的排列反方式排列;

輸出:。。。。

此處不能直接用Collections.reverse();

這樣的話,他會按照相反的順序輸出(2,3,0,1)而不是從大到小;

--------------------------

2.Collections.shuffle()亂序排列。。。。

3.Collections.min();最小

4.Collections.max();最大

還有好多方法在API裏都很詳細,大家可以自己多看看。。。。。。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章