使用比较器排序字符串长度 [英] sorting string lengths using comparator
问题描述
在尝试根据元素字符串长度对数组进行排序时,我遇到了编译错误。我有一套开始,
While trying to sort an array based on its element string lengths, I am struck with a compile error. I have an set to start with, ,
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]
所以我有一个类型为
so I have a comparator of type
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;
}
}
}
然后我打电话给班级by
and then I call the class by
Collections.sort(array, new comp());
然后,它会抛出两个编译错误:
but then, it throws me two compile errors:
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
我很感激任何解决问题的线索。
I would appreciate any clues to solve the problem.
推荐答案
您需要为 Comparator
指定一个类型参数,以使您的实现正常工作。
You need to specify a type parameter for Comparator
for your implementation to work.
class comp implements Comparator<String> {
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;
}
}
}
在Java 1.7及更高版本中,您还可以将此方法的主体简化为:
In Java 1.7 and later, you can also simplify the body of this method to:
class comp implements Comparator<String> {
public int compare(String o1, String o2) {
return Integer.compare(o1.length(), o2.length());
}
}
此外, Collections.sort
排序列出
对象。由于您要对数组进行排序,因此应使用 Arrays.sort
:
Also, Collections.sort
sorts List
objects. Since you're sorting an array, you should use Arrays.sort
:
Arrays.sort(array, new comp());
这篇关于使用比较器排序字符串长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!