正确实现CompareTo

时间:2016-03-16 19:41:26

标签: 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;
    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. 鉴于我的剑class extends WeaponObject,我是否在剑类中正确实施了我的compareTo

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

1 个答案:

答案 0 :(得分:-1)

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;
}