【发布时间】:2013-10-30 12:54:49
【问题描述】:
import java.util.*;
public class C_2 {
public static void main(String args[]) {
String theStrings[] = { "x", "a", "b", "c", "d" };
List l = Arrays.asList(theStrings);
Collections.sort(l); // line a
Collections.sort(l, new ThisIsMyThing()); // line b
System.out.println(l);
}
}
class ThisIsMyThing implements Comparator {
public int compare(Object o1, Object o2) {
String s1 = (String)o1;
String s2 = (String)o2;
return -1 * s1.compareTo(s2);
}
}
我了解C_2 类基于两种不同的技术进行排序。
一种是标准Collections.sort(l);
另一个是Collections.sort(l,Comparator<>());我无法理解这种排序方法。谁能给我解释一下?
【问题讨论】:
-
你不明白什么?你读过文档吗?
-
Collections.sort(l) // line a 这会根据自然顺序对列表进行排序,对吧? Collections.sort(l, new ThisIsMyThing()); // line b 实现了一个 Comparator,其中的参数是 object 类型的。然后类型转换为字符串。在字符串之间进行比较?
-
是的。请注意,您应该使用泛型。
标签: java collections comparator