尝试根据元素字符串长度对数组进行排序时,遇到编译错误。我有一个集下手,使用比较器排序字符串长度
Set<String> arraycat = new HashSet<String>();
//add contents to arraycat
String[] array = arraycat.toArray(new String[0]);
//array looks like this now:
//array=[cat,cataaaa,cataa,cata,cataaa]
我会非常想选到
array=[cat,cata,cataa,cataaa,cataaaa]
,所以我有型的比较
class comp implements Comparator {
public int compare(String o1, String o2) {
if (o1.length() > o2.length()) {
return 1;
} else if (o1.length() < o2.length()) {
return -1;
} else {
return 0;
}
}
}
,然后我调用类的通过
Collections.sort(array, new comp());
但是,它thr ows我两个编译错误:
comp is not abstract and does not override abstract method compare(java.lang.Object,java.lang.Object) in java.util.Comparator
class comp implements Comparator {
^
testa.java:59: cannot find symbol
symbol : method sort(java.lang.String[],comp)
location: class java.util.Collections
Collections.sort(array, new comp());
^2 errors
我将不胜感激任何线索来解决这个问题。
嗨劳伦斯..感谢这..这已经解决了第一个编译错误:但是,我仍然有另一个编译错误说:“找不到符号 符号:方法sort(java.lang.String [], comp) location:class java.util.Collections \t \t收藏。sort(array,new comp());“我已经导入了util *包,不知道为什么我得到这个错误 – JohnJ 2011-12-26 04:23:38
['sort()'](http://docs.oracle.com/javase/6/ docs/api/java/util/Collections.html#sort(java.util.List))使用List而不是String []数组。 /docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList(T ...))来转换它 – 2011-12-26 04:25:14
另外,对于比较简单的比较器,考虑使用['Integer.signum (int)'](http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#signum(int))而不是'if/else-if/else';例如'return Integer.signum(o1.length() - o2.length());' – 2011-12-26 04:26:50