compareTo
public int compareTo(String anotherString)
按字典順序比較兩個字符串。該比較基於字符串中各個字符的 Unicode 值。將此 String 對象表示的字符序列與參數字符串所表示的字符序列進行比較。如果按字典順序此 String 對象在參數字符串之前,則比較結果為一個負整數。如果按字典順序此 String 對象位於參數字符串之後,則比較結果為一個正整數。如果這兩個字符串相等,則結果為 0;compareTo 只有在方法 equals(Object) 返回 true 時才返回 0。
這是字典排序的定義。如果這兩個字符串不同,則要麼它們在某個索引處具有不同的字符,該索引對二者均為有效索引,要麼它們的長度不同,或者同時具備上述兩種情況。如果它們在一個或多個索引位置上具有不同的字符,假設 k 是這類索引的最小值;則按照 < 運算符確定的那個字符串在位置 k 上具有較小的值,其字典順序在其他字符串之前。這種情況下,compareTo 返回這兩個字符串在位置 k 處的兩個不同的 char 值,即值:
this.charAt(k)-anotherString.charAt(k)
如果它們沒有不同的索引位置,則較短字符串在字典順序上位於較長字符串的前面。這種情況下,compareTo 返回這兩個字符串長度的不同,即值:
this.length()-anotherString.length()
指定者:
接口 Comparable 中的 compareTo
參數:
anotherString - 要比較的 String。
返回:
如果參數字符串等於此字符串,則返回 0 值;如果按字典順序此字符串小於字符串參數,則返回一個小於 0 的值;如果按字典順序此字符串大於字符串參數,則返回一個大於 0 的值。
例子:
public class ObjectCompareTo {
private Integer min,max;
public ObjectCompareTo(Integer min, Integer max) {
this.min = min;
this.max = max;
}
public boolean compareTo(Object num){
Comparable compare=(Comparable)num;
int minMatch=compare.compareTo(getMinComparable());
int maxMatch=compare.compareTo(getMaxComparable());
System.out.println(minMatch+"|"+maxMatch);
return minMatch>=0&&maxMatch<=0;
}
public Comparable getMinComparable(){
return this.min;
}
public Comparable getMaxComparable(){
return this.max;
}
public static void main(String[] args) {
Integer minValue=3,maxValue=25;
ObjectCompareTo compareTo=new ObjectCompareTo(minValue,maxValue);
System.out.println(compareTo.compareTo(24));
}
}