叨逼叨两句
- 之前进度慢了,今天睡醒后认真搏一把,看能补回多少——2017.7.10 00:28
- 这上夜班后看书真TM累,真得早决断了。——2017.7.11 00:01
第124集:引用类型-内置类比较-Comparable排序工具类实现
基本概念
- “排序”的实体类都实现了java.lang.Comparable接口【注:实体类和实现类不是一回事】
- Comparable接口只有一个方法:
public int compareTo(Object obj);
-
compareTo方法:
- 返回0,表示this==obj
- 返回负数,表示this<obj
- 返回正数,表示this>obj
- 实现了Comparable接口的类通过实现compareTo方法从而确定该类对象的排序方式。
内置类的Comparable实现
-
IntegerLongBoolean类似
public int compareTo(Integer anotherInteger){ return compare(this.value,anotherInteger.value); }
public static int compare(int x,int y){ return (x<y)? -1 : ((x==y)? 0 : 1); }
-
CharacterByteShort类似
public int compareTo(Charcter anotherInteger){ return compare(this.value,anotherInteger.value); }
public static int compare(char x,char y){ return x - y; }
-
FloatDouble类似
public int compareTo(Float anotherFloat){ return Float.compare(this.value,anotherFloat.value); }
public static int compare(float f1,float f2){ if(f1 > f2){ return 1; } if(f1 < f2){ return -1; } int thisBits = Float.floatToIntBits(f1); int anotherBits = Float.floatToInBits(f2); return (thisBits == anotherBits ? 0: (thisBits > anotherBits ? 1 : -1)); }
-
Date
public int compareTo(Date anotherDate){ long thisTime = getMillisOf(this); long anotherTime = getMillisOf(anotherDate); return (thisTime < anotherTime ? -1 : (thisTime == anotherTime? 0 : 1)); }
-
String
public int compareTo(String anotherString){ int len1 = value.length; int len2 = 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; }
数组(使用泛型方法)排序注意事项
- 泛型可以继承接口【即该泛型是实现Comparable接口的子类】(详见代码)
- 可以将对象强制转换为接口类型(详见代码)
package com.test124;
import java.util.Date;
public class Test124 {
public static void main(String[] args){
}
public static <T extends Comparable<T>> void sort(T[] arr){
boolean sorted= true;
int len = arr.length;
for(int j=0;j<len-1;j++){
sorted = true;
for(int i=0;i<len-1-j;i++){
if(((Comparable)arr[i]).compareTo(arr[i+1])<0){
T temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
sorted = false;
}
}
if(sorted){
break;
}
}
}
}
容器排序注意事项
- 因为没有泛型数组,所以要先转换成Object数组,以其形式排序后,再进行强制转换。
public static <T extends Comparable<T>>void sort(List<T> list){
Object[] arr =list.toArray();
sort(arr);
for(int i=0;i<arr.length;i++){
list.set(i,(T)arr[i]);
}
}