Java 正确执行比较
我有以下课程:Java 正确执行比较,java,subclass,compareto,Java,Subclass,Compareto,我有以下课程: //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;
//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;
}
问题:
类
扩展了武器对象,我是否在剑类中正确实现了我的比较
compareTo
方法武器对象没有
getswordatahment()
方法。因此,您无法基于swordatahment
进行比较。您可以使用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;
}
Swarm.compareTo()
如果尝试与WeaponObject
@shmosel进行比较,则会抛出一个ClassCastException
异常-如何修复它?WeaponObject没有Getswordatament()
方法。因此,你不能基于swordAttahment
@Svetlana进行比较。检查实例显然是一个解决办法,但根据我对@rdonuk答案的评论,这里有更深层的问题更难解决。我的建议是仔细考虑武器
和剑
是否都需要实现可比
和覆盖可比
,或者是否有另一种设置适合您。另一方面,WeaponObject
与Weapon
相比,不是更具描述性的类名。有关更多信息,请参阅讨论。还有一个问题,我可以这样做吗。getClass!=compare.getClass()返回-1?这是你的决定。如果你认为“如果类类型不同,它们一定不同”,你可以这样写。非常感谢你的回答和代码。非常感谢。@Svetlana,绝对不是。你会打破对称,因为w.compareTo(s)==0
而s.compareTo(w)=-1
。返回0将是一个更好的选择,但即使这样也可能破坏传递性,因为您可能会遇到这样一个场景:w.compareTo(s1)==0&&w.compareTo(s2)==0&&s1.compareTo(s2)!=0
。如果扩展swarm
而不重写compareTo()
,您也会遇到问题。无论哪种方式,您都需要确保equals()
实现了文档中推荐的相同逻辑。@shmosel-非常感谢您的建议。对于我正在构建的小文本冒险游戏,我认为compareTo不会被实现。