比较其他类的对象

时间:2013-04-10 09:38:11

标签: java comparable

我有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
}

5 个答案:

答案 0 :(得分:2)

  • 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]) {

答案 1 :(得分:1)

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

答案 2 :(得分:0)

您应该使用if (cakes[0].compareTo( cakes[1]))>0)代替

答案 3 :(得分:0)

使用以下内容:

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

并阅读Comparable documentation

答案 4 :(得分:0)

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

这里没有问题吗? 正如人们所说,你应该使用if(cakes[0].compareTo(cakes[1]) > 0) 好吧,我会说,但你正在使用ArrayList。你能通过输入listname [elementnumber]来获得元素吗?我以为你必须使用listname.get(elementnumber)。