1

我有trouble comparing objects of another class,我该怎么办?
我做了一个很好的例子,希望代码应该是不言自明的。

蛋糕.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
}
4

5 回答 5

2
  • Java 不支持运算符重载,因此以下操作不起作用。
  if (cakes[0] > cakes[1]) {

相反,你应该

if (cakes.get(0).compareTo(cakes.get(1)) > 0) {
  • 另外要从列表中获取元素,我们需要调用list.get(index)not

列表[索引]

所以下面的代码是行不通的。

List<Cake> cakes = new ArrayList<cake>();
// Make a whole lot of cakes here
if (cakes[0] > cakes[1]) {
于 2013-04-10T09:43:26.817 回答
1
if(cakes.get(0).compareTo(cakes.get(1)) > 0) {
    System.out.println("The first cake tastes better than the second");
}
于 2013-04-10T09:42:16.000 回答
0

你应该if (cakes[0].compareTo( cakes[1]))>0)改用

于 2013-04-10T09:41:51.557 回答
0

if (cakes[0] > cakes[1])...

这里没有问题吗?正如人们所说,您应该使用if(cakes[0].compareTo(cakes[1]) > 0) Well I would say that but you're using an ArrayList. 你真的可以通过输入 listname[elementnumber] 来获取元素吗?我以为你必须使用 listname.get(elementnumber)。

于 2013-04-10T09:47:35.267 回答
0

使用以下内容:

if (cakes.get(0).compareTo(cakes.get(1)) > 0) {
    System.out.println("The first cake tastes better than the second");
}

并阅读Comparable 文档

于 2013-04-10T09:42:05.023 回答