A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Dana-乌拉拉 中级黑马   /  2014-11-24 18:11  /  921 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

2)第二种方式:比较器
        当元素自身不具备比较性时,或者具备的比较性不是所需要的。这时就需要让集合自身具备比较性。
        在集合初始化时,就有了比较方式。定义一个比较器,将比较器对象作为参数传递给TreeSet集合的构造函数。
        比较器构造方式:定义一个类,实现Comparator接口,覆盖compare方法。
        当两种排序都存在时,以比较器为主。
示例:
[java] view plaincopy
/*
需求:
往TreeSet集合中存储自定义对象学生。
想按照学生的年龄进行排序。

*/  
  
import java.util.*;  
//学生类  
class Student implements Comparable  
{  
    private String name;  
    private int age;  
    Student(String name,int age)  
    {  
        this.name=name;  
        this.age=age;  
    }  
    public String getName()  
    {  
        return name;  
    }  
  
    public int getAge()  
    {  
        return age;  
    }  
    //复写hashCode以便HashSet集合调用  
    public int hashCode()  
    {  
        return name.hashCode()+age;  
    }  
    //复写equals以便HashSet集合和集合中一些比较方法调用  
    public boolean equals(Object obj)  
    {  
        if(!(obj instanceof Student))  
            throw new RuntimeException();  
        Student s = (Student)obj;  
        return this.name.equals(s.name)&&this.age==s.age;  
    }  
    //复写compareTo以便TreeSet集合调用  
    public int compareTo(Object obj)  
    {  
        Student s=(Student)obj;  
        if(this.age==s.age)  
            return this.name.compareTo(s.name);  
        return this.age-s.age;  
        //return new Integer(this.age).compareTo(new Integer(s.age));   
    }  
  
}  
  
class  TreeSetTest  
{  
    public static void main(String[] args)   
    {  
        TreeSet<Student> t=new TreeSet<Student>(new LenCompare());  
        t.add(new Student("wo1",12));  
        t.add(new Student("wosj",2));  
        t.add(new Student("wo1sdj",12));  
        t.add(new Student("wo6sd",12));  
        t.add(new Student("wo",22));  
  
         
        for (Iterator<Student> it=t.iterator(); it.hasNext(); )  
        {  
            Student s=it.next();  
            System.out.println(s.getName()+"....."+s.getAge());  
        }  
    }  
  
}  
//定义一个比较器,以姓名长度为主要比较  
class LenCompare implements Comparator<Student>  
{  
    public int compare(Student s1,Student s2)  
    {  
        int num=new Integer(s1.getName().length()).compareTo(new Integer(s2.getName().length()));  
        if (num==0)  
        {  
            return new Integer(s1.getAge()).compareTo(s2.getAge());  
        }  
        return num;  
    }  
}  

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马