Compare内置引用数据类型比较:
1、整数、小数、Integer、Float、Doubble类型,直接比较基本数据大小。
2、字符比较unicode码之差。
3、字符串:
1)如果其中一个是另外一个的起始开始的子串,返回长度之差。
2)否则返回第一个不相等的unicode之差。
public int compareTo(String anotherString) { int len1 = value.length; int len2 = anotherString.value.length; int lim = Math.min(len1, len2); char v1[] = value; char v2[] = anotherString.value; int k = 0; while (k < lim) { char c1 = v1[k]; char c2 = v2[k]; if (c1 != c2) { return c1 - c2; } k++; } return len1 - len2; }4、Date 根据日期的长整形进行比较。
public int compareTo(Date anotherDate) { long thisTime = getMillisOf(this); long anotherTime = getMillisOf(anotherDate); return (thisTime<anotherTime ? -1 : (thisTime==anotherTime ? 0 : 1)); }
2、冒泡排序泛型方法
public class SortUtils { /** * 数组按大到小排序(使用泛型方法) * @param arr * @param <T> */ public static <T extends Comparable> void maoPaoSortByMaxToMin(T[] arr){ int len = arr.length; for (int i=0;i<len-1;i++){ //趟数 for (int j=0;j<len-1;j++){ if(arr[j].compareTo(arr[j+1])<0){//次数 T temp = arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } } /** * List按大到小排序 * @param list * @param <T> */ public static <T extends Comparable> void maoPaoSortByList(List<T> list){ //todo } }
3、自定义比较器
public class MyGoods { //名称 public String name; //价格 public double price; //收藏量 public int fav; public MyGoods(String name, double price, int fav) { this.name = name; this.price = price; this.fav = fav; } public static void main(String[] args){ List<MyGoods> list =new ArrayList<>(); list.add(new MyGoods("玉溪",20,100)); list.add(new MyGoods("中华",90,200)); list.add(new MyGoods("长白山",10,1000)); Collections.sort(list,new GoodsPriceComparator()); } }public class GoodsPriceComparator implements java.util.Comparator<MyGoods> { @Override public int compare(MyGoods o1, MyGoods o2) { return o1.price- o2.price>0?1:(o1.price==o2.price?0:-1); } }