JAVA 排序比较器 Comparable 与Comparator

Java中排序主要通过两种方式实现
(1)Collection的sort排序的集合元素都必须是Comparable接口的实现类,该接口表示子类是可以比较的。因为实现接口必须重写抽象方法 - int compareTo(T t)。
(2)使用重载的Collections.sort(List,Comparator)方法,使用匿名内部类的方式, 实现compare(Object o1, Object o2)

DivSort .class文件



public class DivSort implements Comparable<DivSort>{
 public int age;
 public String name;
 public int score;
 
 
 
	public DivSort(int age, String name, int score) {
	super();
	this.age = age;
	this.name = name;
	this.score = score;
}
	public int getAge() {
	return age;
}
public void setAge(int age) {
	this.age = age;
}
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
public int getScore() {
	return score;
}
public void setScore(int score) {
	this.score = score;
}


	@Override
	public int compareTo(DivSort o) {
		// TODO Auto-generated method stub
		int i=this.getAge()-o.getAge();
		return i;
	}

}

Main方法 这里将两种方法都放到一块做实验

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

public class helloword  {
	public static void main(String[] args) {
		System.out.println("Hello Word!");
	 ArrayList<DivSort> list=new ArrayList<DivSort>();
	 list.add(new DivSort(11,"zhangsan",34));
	 list.add(new DivSort(15,"zhangsan",34));
	 list.add(new DivSort(04,"zhangsan",34));
	 list.add(new DivSort(05,"zhangsan",34));
	 list.add(new DivSort(12,"zhangsan",34));
	 
	 Collections.sort(list);
		for(DivSort l:list) {
			System.out.println(l.getAge()+"");
		}

	
	
	Collections.sort(list,new Comparator() {

		@Override
		public int compare(Object o1, Object o2) {
			// TODO Auto-generated method stub
			if(o1 instanceof DivSort && o2 instanceof DivSort) {
				DivSort d1=(DivSort)o1;
				DivSort d2=(DivSort)o2;
				return d1.getAge()-d2.getAge();}
				else {
					throw new ClassCastException("不能转换为Emp类型");
				}
			 
		}
		
	});
	for(DivSort l:list) {
		System.out.println("-----------------");
		System.out.println(l.getAge()+"");
	}


	}
}


你可能感兴趣的:(JAVA基础)