compareTopublic 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<String> 中的 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));
}
}
http://gceclub.sun.com.cn/download/Java_Docs/html/zh_CN/api/index.html這個是jdk中文文檔