我尝试按重量对这些Pet对象进行排序时出现错误。我确定它很简单,但我不明白为什么这种比较不起作用。
错误:返回类型与java.util.Comparator.compare(Pet,Pet)不兼容
ArrayListNoDups类
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
宠物类
import java.util.*;
import java.util.Collections;
import java.util.Comparator;
import java.lang.Object;
public class ArrayListNoDups {
public static void main(String[] args) {
ArrayList<Pet> list = new ArrayList<Pet>();
String name;
Integer age;
Double weight;
Scanner keyboard = new Scanner(System.in);
System.out.println("If you wish to stop adding Pets to the list, please put a 0 for all 3 fields.");
do {
System.out.println("Enter a String for Pet name: ");
name = keyboard.next();
System.out.println("Enter an int for Pet age: ");
age = keyboard.nextInt();
System.out.println("Enter a double for Pet weight: ");
weight = keyboard.nextDouble();
if (name.length() > 0 && age > 0 && weight > 0)
list.add(new Pet(name, age, weight));
} while (name.length() > 0 && age > 0 && weight > 0);
System.out.println("Your list sorted by WEIGHT ========================= ");
Collections.sort(list, Pet.SortByWeight);
for (Pet p2 : list)
p2.writeOutput();
}
}
答案 0 :(得分:7)
compare
接口的 Comparator
方法返回int
,而不是double
。
变化:
public double compare(Pet pet1, Pet pet2)
为:
public int compare(Pet pet1, Pet pet2)
比较器可能如下所示:
public static Comparator<Pet> SortByWeight = new Comparator<Pet>() {
public int compare(Pet pet1, Pet pet2) {
return (int)(pet1.getWeight() - pet2.getWeight());
}
};
答案 1 :(得分:0)
问题是compare需要返回一个整数以符合Comparator
接口。
您可以在比较中转换为int,或者更好,只需使用Double.compare()。
旁注:在这些情况下使用@Override
注释(实现通用接口)将使编译器帮助您更早地看到这些问题。
答案 2 :(得分:0)
试试这个:
public int compare(Pet pet1, Pet pet2) {
return new Double(pet1.getWeight()).compareTo(new Double(pet2.getWeight()));
}