Java基础之TreeSet集合使用泛型、比较器排序示例:

import java.util.*;
class GenericDemo
{
    public static void main(String[] args)
    {
        TreeSet<Person> ts = new TreeSet<Person>(new MyComparator());
        
        ts.add(new Person("张三","男",28,175));
        ts.add(new Person("李四","女",28,160));
        ts.add(new Person("王五","女",27,185));
        ts.add(new Person("麻六","男",38,174));
        
        for(Iterator<Person> it = ts.iterator();it.hasNext();)
        {
            Person p = it.next();
            System.out.println(p.getName()+"\t"+p.getSex()+"\t"+p.getAge()+"\t"+p.getHeight());
        }
    }
}

class MyComparator implements Comparator<Person>
{
    public int compare(Person p1,Person p2)
    {
        if(p2.getName().equals(p1.getName()))
        {
            if(p2.getAge()==p1.getAge())
            {
                return 0;
            }
        }
        
        return p2.getName().compareTo(p1.getName());
    }
}

class Person implements Comparable
{
    private String name;
    private String sex;
    private int age;
    private int height;
    
    public Person(String name,String sex,int age,int height)
    {
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.height = height;
    }
    
    public void setName(String name)
    {
        this.name = name;
    }
    
    public String getName()
    {
        return this.name;
    }
    
    public void setSex(String sex)
    {
        this.sex = sex;
    }
    
    public String getSex()
    {
        return this.sex;
    }
    
    public void setAge(int age)
    {
        this.age = age;
    }
    
    public int getAge()
    {
        return this.age;
    }
    
    public void setHeight(int height)
    {
        this.height = height;
    }
    
    public int getHeight()
    {
        return this.height;
    }
    
    public int compareTo(Object obj)
    {
        if(!(obj instanceof Person))
            return -1;
            
        Person p = (Person)obj;
        int number = this.getName().compareTo(p.getName());
        if(number==0)
        {
            return this.getAge() - p.getAge();
        }
        
        return number;
    }
    
    public int hashCode()
    {
        return this.getName().hashCode()+this.getAge()*21;
    }
    
    public boolean equals(Object obj)
    {
        if(!(obj instanceof Person))
            return false;
            
        Person p = (Person)obj;
        
        return (p.getName().equals(this.getName()) && p.getAge()==this.getAge());
    }
}
原文地址:https://www.cnblogs.com/cxmsky/p/2863929.html