gpt4 book ai didi

java - 无法使用 Comparable 接口(interface)正确比较生物体 - Java

转载 作者:行者123 更新时间:2023-12-01 18:27:41 25 4
gpt4 key购买 nike

所以我在 Java 中有一个小的“虚拟世界”项目,其中有四个动物(它们扩展了有机体类)。其中每一个(羚羊、狐狸、乌龟、狼)都有一个“主动性”、“力量”和“年龄”字段(均为整数)。我想将它们放入数组中,然后将其排序,将最高的主动性放在最上面,如果两只动物的主动性相同,则年龄较大的动物更高。因此,为了比较这些,我的抽象类“Organism”实现了 Comparable 接口(interface),并重写了compareTo 方法,所以它看起来像这样:

    @Override
public int compareTo(Organism anotherOrganism) {
int compareValue = 0;

if (this.getInitiative() > anotherOrganism.getInitiative()){
compareValue = 1;
} else if (this.getInitiative() < anotherOrganism.getInitiative()){
compareValue = -1;
} else if (this.getInitiative() == anotherOrganism.getInitiative()){
if (this.getAge() > anotherOrganism.getAge()){
compareValue = 1;
} else {
compareValue = -1;
}
}
return compareValue;
}

我按照以下顺序将这些动物输入数组(括号中的数字是它们的实际主动性):狐狸(7)->乌龟(1)->羚羊(4)->狼(5),然后使用

        Collections.sort(organismList);

期望这会导致

 Fox, Wolf, Antelope, Turtle

我收到的不是这个

 Wolf, Antelope, Turtle, Fox

这里出了什么问题?显然动物也实现了compareTo方法(它们引用了Organism中的super.compareTo)

编辑:是的,所以根据下面的建议,代码相当好,我已经从动物中删除了任何主动性(该字段留空),并且我仍然得到相同的输出。不知道为什么......

最佳答案

我已将代码扩展为 Meal Ready to Eat 。它打印出预期的内容。

[Organism$1Turtle, Organism$1Antelope, Organism$1Wolf, Organism$1Fox]

代码:

import java.util.*;

abstract class Organism implements Comparable<Organism> {
public static void main(String[] args) throws Throwable {
class Fox extends Organism {
@Override public int getInitiative() {
return 7;
}
}
class Turtle extends Organism {
@Override public int getInitiative() {
return 1;
}
}
class Antelope extends Organism {
@Override public int getInitiative() {
return 4;
}
}
class Wolf extends Organism {
@Override public int getInitiative() {
return 5;
}
}
List<Organism> organismList = Arrays.asList(
new Fox(), new Turtle(), new Antelope(), new Wolf()
);

Collections.sort(organismList);

System.err.println(organismList);
}
@Override public String toString() {
return getClass().getName();
}
public abstract int getInitiative();
public int getAge() {
return 42;
}
@Override
public int compareTo(Organism anotherOrganism) {
int compareValue = 0;

if (this.getInitiative() > anotherOrganism.getInitiative()){
compareValue = 1;
} else if (this.getInitiative() < anotherOrganism.getInitiative()){
compareValue = -1;
} else if (this.getInitiative() == anotherOrganism.getInitiative()){
if (this.getAge() > anotherOrganism.getAge()){
compareValue = 1;
} else {
compareValue = -1;
}
}
return compareValue;
}
}

关于java - 无法使用 Comparable 接口(interface)正确比较生物体 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60206741/

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