gpt4 book ai didi

java - 正确实现 CompareTo

转载 作者:行者123 更新时间:2023-12-01 06:10:33 24 4
gpt4 key购买 nike

我有以下类(class):

//GetHasCode, toString, and equalsTo removed to keep the question simple.
private String weaponName;
private String weaponType;
private int weaponDamage;

public WeaponObject(String name, String type, int damage)
{
this.weaponName = name;
this.weaponType = type;
this.weaponDamage = damage;
}

@Override
public int compareTo(WeaponObject compare) {

int name = this.getWeaponName().compareTo(compare.getWeaponName());
int type = this.getWeaponType().compareTo(compare.getWeaponType());
int damage = Integer.compare(this.weaponDamage, compare.getWeaponDamage());

if(name !=0 )
{
return name;
}
if(type != 0)
{
return type;
}
if(damage != 0)
{
return damage;
}
return 0;

}

子类:

public class Sword extends WeaponObject {


private String swordAttahment;

public Sword(String name, String type, int damage, String attachment) {
super(name, type, damage);
this.swordAttahment = attachment;
}


public String getSwordAttahment() {
return swordAttahment;
}


@Override
public int compareTo (WeaponObject compare)
{
int superCompare = super.compareTo(compare);

if(superCompare != 0)
{
return superCompare;
}

Sword other = (Sword)compare;

int attach = this.getSwordAttahment().compareTo(other.getSwordAttahment());

if(attach != 0)
{
return attach;
}

return 0;
}

问题:

  1. 鉴于我有一个扩展 WeaponObject 的 Sword class,我是否在 Sword 类中正确实现了我的 compareTo

  2. 如果上述不正确,那么我如何在子类中正确实现 compareTo 方法?

最佳答案

WeaponObject 没有 getSwordAttahment() 方法。所以你不能根据swordAttahment进行比较。您可以使用 instanceof 来避免 ClassCastException

@Override
public int compareTo (WeaponObject compare)
{
int superCompare = super.compareTo(compare);

if(superCompare != 0)
{
return superCompare;
}

if(compare instanceof Sword) {
Sword other = (Sword)compare;

int attach = this.getSwordAttahment().compareTo(other.getSwordAttahment());

if(attach != 0)
{
return attach;
}
}

return 0;
}

关于java - 正确实现 CompareTo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36045473/

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