comparable & compartor

public class Student implements Comparable<Student>{
	
	private Integer no;
	private String name;
	
	
	public Integer getNo() {
		return no;
	}
	public void setNo(Integer no) {
		this.no = no;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	@Override
	public int compareTo(Student o) {
		return (this.no - o.getNo());
	}
	
	public Student(Integer no, String name) {
		this.no = no;
		this.name = name;
	}

}
import java.util.Comparator;

public class StudentComparator implements Comparator<Student>{

	@Override
	public int compare(Student o1, Student o2) {
		return (o1.getNo() - o2.getNo());
	}
	
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TestCompare {

	public static void main(String[] args) {
		
		List<Student> list = new ArrayList<Student>();
		list.add(new Student(3, "3"));
		list.add(new Student(2, "2"));
		list.add(new Student(1, "1"));
		
		// 相当于外部比较器
		list.sort(new StudentComparator());
		System.out.println("comparator");
		for(Student s : list) {
			System.out.println(s.getName());
		}
		// 相当于内部比较器
		System.out.println("comparable");
		list.add(new Student(6, "6"));
		list.add(new Student(5, "5"));
		list.add(new Student(4, "4"));
		
		System.out.println("sort before");
		for(Student s : list) {
			System.out.println(s.getName());
		}
		
		System.out.println("sort after");
		Collections.sort(list);
		for(Student s : list) {
			System.out.println(s.getName());
		}
	}
}

 

转载于:https://my.oschina.net/u/2308196/blog/3024534

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值