本文介绍了正确实现 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. 鉴于我有一个 extends WeaponObject 的 Sword class,我是否在 Sword 类中正确实现了我的 compareTo?

  1. Given that I have a Sword class that extends WeaponObject, have I correctly implemented my compareTo in the Sword class?

如果以上不正确,那么我将如何在我的子类中正确实现 compareTo 方法?

If the above isn't correct, then how would I correctly implement the compareTo method in my subclass?

推荐答案

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

WeaponObject doesn't have getSwordAttahment() method. So you can not make a comparison based on swordAttahment. You can use instanceof to avoid 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;
}

这篇关于正确实现 CompareTo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 05:20