オブジェクトのソート

3180 ワード

Javaオブジェクトを複数の列でソートします.
Personクラスは、ageでソートし、ageが等しい場合はnameでソートします.
 
Person:
package com.weye.bean;

public class Person implements Comparable<Person>
{
    private int age;
    
    private String name;
    
    private int sex;
    
    /**
     * @return the age
     */
    public int getAge()
    {
        return age;
    }
    
    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString()
    {
        return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";
    }
    
    /**
     * @param age the age to set
     */
    public void setAge(int age)
    {
        this.age = age;
    }
    
    /**
     * @return the name
     */
    public String getName()
    {
        return name;
    }
    
    /**
     * @param name the name to set
     */
    public void setName(String name)
    {
        this.name = name;
    }
    
    /**
     * @return the sex
     */
    public int getSex()
    {
        return sex;
    }
    
    /**
     * @param sex the sex to set
     */
    public void setSex(int sex)
    {
        this.sex = sex;
    }

    /* (non-Javadoc)
     * @see java.lang.Comparable#compareTo(java.lang.Object)
     */
    @Override
    public int compareTo(Person o)
    {
        //  age 
        int result = this.age - o.age;
        
        if (result == 0) //  age , 
        {
            result = this.name.compareTo(o.name); // name String ,String CompareTo 
        }
        return result;
    }
}


 
mainメソッド:
Person p1 = new Person();
        p1.setName("ab");
        p1.setAge(13);
        
        Person p2 = new Person();
        p2.setName("ya");
        p2.setAge(25);
        
        Person p3 = new Person();
        p3.setName("li");
        p3.setAge(20);
        
        Person p4 = new Person();
        p4.setName("ac");
        p4.setAge(13);
        
        List list = new ArrayList();
        list.add(p3);
        list.add(p2);
        list.add(p1);
        list.add(p4);
        
        
        System.out.println(list);
        Collections.sort(list);
        System.out.println(list);

 
 
出力:
 :[Person [name=li, age=20, sex=0], Person [name=ya, age=25, sex=0], Person [name=ab, age=13, sex=0], Person [name=ac, age=13, sex=0]]

 :[Person [name=ab, age=13, sex=0], Person [name=ac, age=13, sex=0], Person [name=li, age=20, sex=0], Person [name=ya, age=25, sex=0]]