Comparable,Comparator,compare,compareTo的区别和应用

public class ArrayTest {
	public static void main(String[] args){
                 List<Students> list = new ArrayList<Students>();
		list.add(new Students(3,"langhua"));
		list.add(new Students(2,"xia"));
		list.add(new Students(2,"array"));
		list.add(new Students(1,"ffein"));
		Collections.sort(list, new Students.MyComparator());
                  //这是反序排序Collections.sort(list, Collections.reverseOrder());
                  //Array.sort(Object[] o,Comparator c);针对对象数组也可以排序
		System.out.println(list);
         }
}
class Students implements Comparable{
	int num;
	String name;
	static class MyComparator implements Comparator{

		public int compare(Object o1, Object o2) {
			Students s1 = (Students) o1;
			Students s2 = (Students) o2;
			int result = s1.num > s2.num ? 1 : (s1.num == s2.num ? 0 : -1);
			if(result==0){
				return s1.name.compareTo(s2.name);
			}
			return result;
		}
		
	}
	public Students(int num,String name){
		this.num = num;
		this.name = name;
	}
	public String toString(){
		return num+":"+name;
	}
	public int compareTo(Object o) {
		Students s = (Students) o;
		int result =  num>s.num ? 1:(num==s.num ? 0:-1);
		if(result == 0){
			result = name.compareTo(s.name);
			return result;
		}
		return result;
	}
}
//对comparator理解还不是很深刻
//Collections.min(Collection<? extends T> coll) 
//Collections.binarySearch(List<? extends Comparable<? super T>> list, T key)等方法

你可能感兴趣的:(C++,c,C#)