1. 程式人生 > >集合排序(list)

集合排序(list)

1.Comparable自然規則排序
//在自定義類Student裡面實現Comparable介面,並重寫抽象方法compareTo(Student o);
//Collections.sort(集合);

    public static void main(String[] args) {  
        List<Integer> nums = new ArrayList<Integer>();  
            nums.add(3);  
            nums.add(5);  
            nums.add(1);  
            nums.add(0);  
            System.out.println(nums);  
            Collections.sort(nums);  
            System.out.println(nums);  
    } 

輸出結果:
[3, 5, 1, 0]
[0, 1, 3, 5]

 

稍微複雜的List裡面放一個複雜的物件

package core.java.collection.collections;  
 
public class User implements Comparable<User>{  
      
    private int score;  
      
    private int age;  
      
    public User(int score, int age){  
        super();  
        this.score = score;  
        this.age = age;  
    }  
 
    public int getScore() {  
        return score;  
    }  
 
    public void setScore(int score) {  
        this.score = score;  
    }  
 
    public int getAge() {  
        return age;  
    }  
 
    public void setAge(int age) {  
        this.age = age;  
    }  
 
    @Override  
    public int compareTo(User o) {  
        int i = this.getAge() - o.getAge();//先按照年齡排序  
        if(i == 0){  
            return this.score - o.getScore();//如果年齡相等了再用分數進行排序  
        }  
        return i;  
    }  
      
}  
 
public static void main(String[] args) {  
        List<User> users = new ArrayList<User>();  
        users.add(new User(78, 26));  
        users.add(new User(67, 23));  
        users.add(new User(34, 56));  
        users.add(new User(55, 23));  
        Collections.sort(users);  
        for(User user : users){  
            System.out.println(user.getScore() + "," + user.getAge());  
        }  
}