对象排序

给对象排序


package jihe;

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

/**
 * 测试list
 * xutengteng
 * 2017-9-19
 */
public class ListTest {

	public static void main(String[] args) {
		
		listSort();
		
	}
	
	/**测试list排序*/
	public static void listSort(){
		Student stu1 = new Student();
		stu1.setAge(18);
		Student stu2 = new Student();
		stu2.setAge(11);
		Student stu3 = new Student();
		stu3.setAge(15);
		Student stu4 = new Student();
		stu4.setAge(12);
		List<Student> stuList = new ArrayList<Student>();
		stuList.add(stu1);
		stuList.add(stu2);
		stuList.add(stu3);
		stuList.add(stu4);
		Collections.sort(stuList, new ListComparator());
		System.out.println("===========降序排列==========");
		for (int i = 0; i < stuList.size(); i++) {
			System.out.println(stuList.get(i).getAge()); //降序排列
		}
		Collections.sort(stuList, new ListComparators());
		System.out.println("===========升序排列==========");
		for (int i = 0; i < stuList.size(); i++) {
			System.out.println(stuList.get(i).getAge()); //升序排列
		}
	}
	
	
}

class Student{
	
	private int age;

	public int getAge() {
		return age;
	}

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

class ListComparator implements Comparator<Student>{

	@Override
	public int compare(Student o1, Student o2) {
		//降序排列
		if(o2.getAge()>o1.getAge()){
			return 1;
		}
		if(o2.getAge()<o1.getAge()){
			return -1;
		}
		return 0;
	}
	
}

class ListComparators implements Comparator<Student>{
	
	@Override
	public int compare(Student o1, Student o2) {
		//升序排列
		if(o2.getAge()<o1.getAge()){
			return 1;
		}
		if(o2.getAge()>o1.getAge()){
			return -1;
		}
		return 0;
	}
	
}
打印的结果
===========降序排列==========
18
15
12
11
===========升序排列==========
11
12
15
18


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值