TreeSet的学习和使用

来源:互联网 发布:网红淘宝店 编辑:程序博客网 时间:2024/05/16 03:05
2011-06-07 19:34

/*
 
TreeSet:它可以给Set集合中的元素进行指定方式的排序。
        保证元素唯一性的方式:通过比较的结果是否为0.
        底层数据结构是:二叉树。
*/
 
 
import java.util.*;

 
class TreeSet2  
{
    public static void main(String[] args)  
    {
        TreeSet ts = new TreeSet();
 
        ts.add(new Student("lisi0",30));
        ts.add(new Student("lisixx",29));
        ts.add(new Student("lisi9",29));
        ts.add(new Student("lisi8",38));
        ts.add(new Student("lisixx",29));
        ts.add(new Student("lisi4",14));
        ts.add(new Student("lisi7",27));
 
        System.out.println(ts);
    }
}
 
//同姓名同年龄的学生视为同一个学生。按照学生的年龄排序。
class Student implements Comparable
{
    private int age;
    private String name;
    Student(String name,int age)
    {
        this.age = age;
        this.name = name;
    }
 
    public int compareTo(Object obj)
    {
        
        Student stu = (Student)obj;
        
        int num = new Integer(this.age).compareTo(new Integer(stu.age));
 
        return num==0?this.name.compareTo(stu.name):num; 年龄相同则按姓名排序
 
        /*
        if(this.age>stu.age)
            return 1;
        if(this.age==stu.age)
            return this.name.compareTo(stu.name);
        return -1;
        */
        /**/
    }
 
    public int getAge()
    {
        return age;
    }
    public String toString()
    {
        return name+"::"+age;
    }
}

 

=============================================


/*
 
TreeSet:它可以给Set集合中的元素进行指定方式的排序。
        保证元素唯一性的方式:通过比较的结果是否为0.
        底层数据结构是:二叉树。
 
        排序的第一种方式:
            让元素自身具备比较性。只要让元素实现Comparable接口,覆盖compareTo方法即可。
            
            但是,如果元素自身不具备比较性,或者元素自身具备的比较性,不是所需要的。
            比如,学生的自然排序是按年龄排序,现在想要按照学生姓名排序。还可以不改动原有代码。
            这时怎么办呢?
        排序的第二种方式:自定比较器的方式。
            这时可以让集合自身具备比较性。
            可以定义一个类实现Comparator接口,覆盖compare方法。将该Comparator接口子类对象作为实际参数
            传递给TreeSet集合构造函数。
 
            该对象就是比较器。
 
 
 
*/
 
 
import java.util.*;
 
 
class TreeSet3  
{
    public static void main(String[] args)  
    {
        TreeSet ts = new TreeSet(new StudentComparatorByName());
 
        ts.add(new Student("lisi0",30));
        ts.add(new Student("lisixx",29));
        ts.add(new Student("lisi9",29));
        ts.add(new Student("lisi8",38));
        ts.add(new Student("lisixx",29));
        ts.add(new Student("lisi4",14));
        ts.add(new Student("lisi7",27));

        System.out.println(ts);
    }
}
 
class StudentComparatorByName implements Comparator
{
    public int compare(Object o1,Object o2)
    {
        Student s1 = (Student)o1;
        Student s2 = (Student)o2;
 
        int num = s1.getName().compareTo(s2.getName());
        return num==0?new Integer(s1.getAge()).compareTo(new Integer(s2.getAge())):num;
    }
}
 

0 0
原创粉丝点击