TreeSet的特性

風痕影默發表於2014-09-16

TreeSet在Set的元素不重複的基礎之上引入排序的概念,其中對自身擁有Comparable的元素,可以直接進行排序,比如字串,按照字母的自然順序排序,此處說下對於自定義物件排序的方式。

1、儲存元素的類實現Comparable介面

實現Comparable介面,其中只有一個方法

compareTo(Object obj)

obj:是用來比較的物件,也就是前邊進入TreeSet的物件

繼續以Person來舉例,首先實現Person類,程式碼如下:

class Person implements Comparable
{
    private String name;
    private int age;

    public Person(String name, int age)
    {
        this.name = name;
        this.age = age;
    }
        //特別要注意的是此處也是TreeSet識別重複元素的規則,當年齡一樣的時候要判斷姓名是否相同,否則若年齡相同的話就不能存入TreeSet
    public int compareTo(Object obj)
    {
        if(!(obj instanceof Person))
            throw new RuntimeException("hehe");
        Person p = (Person)obj;
        int ageGap = this.age - p.age; 
        if(ageGap > 0)
            return 1;
        else if(ageGap < 0)
            return -1;
        else
            return this.getName().compareTo(p.getName());
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public void setAge(int age)
    {
        this.age = age;
    }

    public String getName()
    {
        return this.name;
    }

    public int getAge()
    {
        return this.age;
    }
}

2、建立TreeSet時向其中加入Comparator

當元素不具備比較性時,此時只能為容器新增比較器來解決問題,當元素具備比較性,並且容器具備比較器,此時要以比較器為主。

繼續以Person作為例子

定義Comparator

//注意Comparator是一個泛型介面
class PersonComparator implements Comparator<Person>
{
    public int compare(Person p1, Person p2)
    {
        int number = p1.getName().compareTo(p2.getName());
                //先判斷姓名,再判斷年齡,和Comparable一樣的,只比較一個條件會導致另一個條件不同的元素無法存入TreeSet
        if(number == 0)
            return new Integer(p1.getAge()).compareTo(new Integer(p2.getAge()));
        else
            return number;
    }
}

如何使用

public class Test
{
    public static void main(String[] args)
    {    
                //TreeSet的構造方法中有用於接收比較器
                TreeSet<Person> ts = new TreeSet<>(new PersonComparator());

        ts.add(new Person("zhangsi", 34));
        ts.add(new Person("zhangsi", 25));
        ts.add(new Person("lisi", 34));
        ts.add(new Person("zhangsi", 567));
        ts.add(new Person("wangwu", 84));
        ts.add(new Person("zhangsi", 23));

        Iterator<Person> it = ts.iterator();

        while(it.hasNext())
        {
            Person p = it.next();
            System.out.println(p.getName()+"%%%%%"+p.getAge());
        }
    }
}

 

相關文章