我有这个方法,但是它返回错误MyComparator不是抽象的,并且没有超过我也尝试使用Present而不是PresentInterface的抽象方法,因为我已经在当前类中实现了当前接口。我最终想要对存在的数组列表进行排序 非常感谢任何帮助,谢谢
public class MyComparator implements Comparable<PresentInterface>{
// The name of the present, e.g. "one directions greatest hits"
private String name;
// The type of the present, e.g. music, sweets, dvds, games.
private String type;
//The cost of the present, e.g. £11.99
private double cost;
/**
* Sets the name of the present.
*
* @param - name - the name of the present.
*/
public void setName(String name) {
this.name = name;
}
/**
* Sets the type of the present.
*
* @param - type - the type of the present.
*/
public void setType(String type) {
this.type = type;
}
/**
* Sets the cost of the present.
*
* @param - cost - the cost of the present.
*/
public void setCost(double cost) {
this.cost = cost;
}
/**
* Gets the name of the present.
*
* @return - the name of the present.
*/
public String getName() {
return name;
}
/**
* Gets the type of the present.
*
* @return - the type of the present.
*/
public String getType() {
return type;
}
/**
* Gets the cost of the present.
*
* @return - the cost of the present.
*/
public double getCost() {
return cost;
}
/**
* Converts the fields in this present object to a nicer string representation.
*
* @return - the present information in the form of a string: name - type - cost.
*/
public String toString() {
return name + " - " + type + " - " + cost;
}
@Override
public double compare( Present a){
return this.cost.compareTo(a.getCost());
}
答案 0 :(得分:2)
你要覆盖错误的方法。它应该是
@Override
public int compareTo(PresentInterface other) {
return this.cost.compareTo(other.getCost());
}
正如fge所说,API将告诉您解决此问题和类似问题需要了解的一切。请看一下。
如果要将您的类用作Comparator,那么它应该实现Comparator接口,而不是Comparable接口。然后比较方法应该采用两个参数。否则,如果该类确实是一个Comparable,那么Comparable接口的泛型应该是类本身的泛型。
答案 1 :(得分:0)
您应该实施public int compareTo( PresentInterface a)
而不是public double compare( Present a)