自定义的排序比较器Comparator

package com.javabase.obj.comparator;

import java.util.Comparator;

/**自定義比較器类,用於比較學生的成績,定義的時候一定要給泛型
 * @author Administrator
 *
 */
public class Compared implements Comparator<Student>{

	@Override
	public int compare(Student o1, Student o2) {
		//定義規則
		if (o1.getCore()>o2.getCore()) {
			return 1;
		} else if(o1.getCore()<o2.getCore()){
            return -1;
		}
		return 0;
	}

}

//学生类,比较的对象

package com.javabase.obj.comparator;

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

/**比較的對象類
 * @author Administrator
 *
 */
public class Student {
	//姓名
	private String name;
	//班級
	private String glass;
	//成績
	private double core;
	
	public Student() {
		super();

	}

	public Student(String name, String glass, double core) {
		super();
		this.name = name;
		this.glass = glass;
		this.core = core;
	}

	public String getName() {
		return name;
	}
	public String getGlass() {
		return glass;
	}
	public double getCore() {
		return core;
	}

	@Override
	public String toString() {
		return this.name+"--"+this.glass+""+this.core;
	}



	//測試比較器的方法
	public static void main(String[] args) {
		//創建一個集合
		ArrayList< Student> list=new ArrayList<Student>();
//		/添加元素
		list.add(new Student("zhangsan","三班",60));
		list.add(new Student("李四","三班",60));
		list.add(new Student("王二","三班",80));
		list.add(new Student("碼子","三班",68));
		list.add(new Student("狗蛋","三班",80));
		list.add(new Student("水哥","三班",40));
		//沒有使用比較器的時候是亂序的
//		for (Student stu : list) {
//			System.out.println(stu);
//		}
		//使用比較器進行輸出,list是比較的集合,後面的對象是定義的比較器
		Collections.sort(list,new Compared());
		for (Student stu : list) {
			System.out.println(stu);
		}
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值