1. 程式人生 > >List集合裡面按照人的年齡屬性排序

List集合裡面按照人的年齡屬性排序

目的:將裝入ArrayList集合裡面的物件按照物件年齡排序。

方法實現:通過實現Comparable介面,重寫compareTo()方法實現。

User.java

package com.zmj.javase.listsort;

/**
 * 通過實現Comparable介面,重寫compareTo()方法實現
 * @author zhou
 *
 */
public class User implements Comparable<User> {
	private String name;
	private int age;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public User(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	
	@Override
	public int compareTo(User o) {
		if(o.age>this.age){
			return 1;
		}else if(o.age>this.age){
			return 0;
		}else{
			return -1;
		}
	}	
}
LIstSortMain.java
package com.zmj.javase.listsort;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 測試類
 * @author 周
 *
 */
public class ListSortDemo {
	public static void main(String[] args) {
		
		List<User> list = new ArrayList<User>();
		
		list.add(new User("zhou", 12));
		list.add(new User("meng", 11));
		list.add(new User("jun", 13));
		
		Collections.sort(list);//通過Collections類的sort()方法排序
		//遍歷
		for(User user : list){
			System.out.println(user.getAge());
		}
	}
}
執行無誤。吐舌頭