gpt4 book ai didi

java - 比较其他类的对象

转载 作者:行者123 更新时间:2023-11-29 05:45:40 26 4
gpt4 key购买 nike

我在比较另一个类的对象时遇到问题,我应该如何进行?
我做了一个很好的例子,希望代码应该是不言自明的。

蛋糕.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[index]

所以下面的代码将不起作用。

List<Cake> cakes = new ArrayList<cake>();
// Make a whole lot of cakes here
if (cakes[0] > cakes[1]) {

关于java - 比较其他类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15922200/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com