我正在使用trouble comparing objects of another class
,我应该如何进行?
我做了一个很好的例子,希望代码应该是不言自明的。
cake.java:
public class Cake implements Comparable<Cake> {
private final int tastyness;
public Cake(tastyness) {
this.tastyness = tastyness;
}
public int compareTo(Cake other) {
return this.tastyness - other.tastyness;
}
}
makeBestDinner.java:
public class makeBestDinner {
List<Cake> cakes = new ArrayList<cake>();
// Make a whole lot of cakes here
if (cakes[0] > cakes[1]) {
System.out.println("The first cake tastes better than the second");
}
// Do the same for beverages
}
最佳答案
Java不支持运算符重载,因此以下操作不会
工作。
if (cakes[0] > cakes[1]) {
相反,你应该
if (cakes.get(0).compareTo(cakes.get(1)) > 0) {
另外,要从列表中获取元素,我们需要调用
list.get(index)
清单[索引]
因此,以下代码将不起作用。
List<Cake> cakes = new ArrayList<cake>();
// Make a whole lot of cakes here
if (cakes[0] > cakes[1]) {