`
yxx676229549
  • 浏览: 72535 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

list内对象的属性的排序

阅读更多

package mianshi;

public class Student {

	int id;
	String name;
	double score;
	int age;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getScore() {
		return score;
	}

	public void setScore(double score) {
		this.score = score;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}
 package mianshi;
import java.util.Comparator;

public class ComparatorStudent implements Comparator<Object> {


	@Override
	public int compare(Object o1, Object o2) {
		Student s1 = (Student) o1;
		Student s2 = (Student) o2;
		int i=0 ;
		if(s1.getAge() == s2.getAge()){
			i= 0;
		}else if(s1.getAge() > s2.getAge()){
			i= 1;
		}else if(s1.getAge() < s2.getAge()){
			i= -1;
		}
		return i ;
	}

}
 package mianshi;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

public class ListSort {

    List list = new ArrayList();
	
	public static void main(String[] args) {
		ListSort listSort = new ListSort();
		listSort.addStudent(1, "one", 100, 23);
		listSort.addStudent(2, "two", 100, 20);
		listSort.addStudent(3, "three", 100, 16);
		listSort.addStudent(4, "four", 100, 24);
		
		ComparatorStudent comparator = new ComparatorStudent();
		Collections.sort(listSort.list, comparator);
		
		
		Iterator<Student> iterator = listSort.list.iterator();
		while(iterator.hasNext()){
			System.out.println(iterator.next().age);
		}
		
	}
	
	public void addStudent(int id,String name,double score,int age){
		Student student = new Student();
		student.setId(id);
		student.setName(name);
		student.setScore(score);
		student.setAge(age);
		list.add(student);
	}
	
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics