先说明一下其用途,这两个方法都是用来排序用的。见名也应知其义,与什么比较。
compareTo():String类的方法
public native int compareTo(String string);
public int compareTo (String string)
Added in API level 1
Compares this string to the given string. The strings are compared one char at a time.
In the discussion of the return value below, note that char does not mean code point, though this should only be visible for surrogate pairs.
If there is an index at which the two strings differ, the result is the difference between the two chars at the lowest such index. If not, but the lengths of the strings differ, the result is the difference between the two strings' lengths. If the strings are the same length and every char is the same, the result is 0.
Throws NullPointerException if string is null.
我的翻译:
调用此方法的字符串和传进来的字符串比较。挨次(挨着一个一个)比较每一字符。
结果(返回值)有多种情况:
如果两个字符串完全一样(长度和每个位置上的字符),返回0。
例如:"ad".compreTo("ad"); return 0;
如果当某个位置上字符不一样,则返回其int值之差。
例如:"ad".compreTo("ab); return (int)d - (int)b = 2
如果当长度不一样,而已有的字符全都一样,则返回长度之差。
例如:"ad".compreTo("adc"); return 2 - 4 = -2;
都是前面减去后面。
compare():Comparetor<T>接口的方法
public int compare(T lhs, T rhs);
public int compare(T lhs, T rhs)
Description copied from interface:
Comparator Compares the two specified objects to determine their relative ordering. The ordering implied by the return value of this method for all possible pairs of (lhs, rhs) should form an equivalence relation.
This means that
compare(a,a) returns zero for all a the sign of compare(a,b) must be the opposite of the sign of compare(b,a) for all pairs of (a,b) From compare(a,b) > 0 and compare(b,c) > 0 it must follow compare(a,c) > 0 for all possible combinations of (a,b,c) Specified by: compare in interface Comparator Parameters: lhs - an Object. rhs - a second Object to compare with lhs.
Returns:
an integer < 0 if lhs is less than rhs, // 返回值小于0,则lhs<rhs
0 if they are equal, // 返回值为0,则lsh与rhs相等
and > 0 if lhs is greater than rhs.a // 返回值大于0,则lhs>rhs
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(4);
list.add(3);
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer lhs, Integer rhs) {
Log.e(TAG, "compare: " + lhs + "," + rhs );
// 分别是 2,1。得出最小的1,放在最前面。 1 <- 2
// 然后是 4,2。4 > 2,放在后面。 1, 2 <- 4
// 然后是 3,4。3 < 4,放在4前面。然后判断是否还可以往前。 1, 2, 4 <- 3
// 3和2比,3 > 2, 3放在2后面。结束比较
// 结果为1, 2, 3, 4。
return lhs.compareTo(rhs);
// l -> r asc 升序
// r -> l desc 降序
}
});