【问题标题】:Generic Array Java通用数组 Java
【发布时间】:2015-01-28 02:31:26
【问题描述】:
/**
 * Compares this array with another array.
 * <p>
 * This is a requirement of the Comparable interface.  It is used to provide
 * an ordering for Array elements.
 * @return a negative value if the provided array is "greater than" this array,
 * zero if the arrays are identical, and a positive value if the
 * provided array is "less than" this array.
 */
@Override

public int compareTo(Array s) {
    // TODO - you fill in here (replace 0 with proper return
    // value).
        for (int i = 0; i < Math.min(s.size(), mSize); i++) {
        if (this.mArray[i] != s.mArray[i]) {
            return mArray[i] - s.mArray[i];   //FAIL HERE
        }
    }

    return size() - s.size();
}

错误:运算符 - 未定义参数类型 Array&lt;T&gt;Array。有人可以告诉我如何返回 2 个数组元素之间的差异吗?

谢谢。

【问题讨论】:

  • 你的 mArray 数组类型是 int 吗?
  • 如果Array是你自定义的类型,你应该改成别的名字,因为它是JDK中的类名。
  • 私有数组 [] mArray;它可以是任何类型
  • 你希望运算符-如何应用于Array对象?
  • 哦,嗯,但我认为我正在做的是减去数组的元素.....

标签: java generics generic-programming subtraction


【解决方案1】:

如果您确定数组元素是 int,您可以尝试执行 Integer.parseInt()。同样,您也可以强制强制转换。

方法一:

if (this.mArray[i] != s.mArray[i]) {
    return Integer.parseInt(mArray[i]) - Integer.parseInt(s.mArray[i]);
}

方法B:

if (this.mArray[i] != s.mArray[i]) {
    return ((int) mArray[i]) - ((int) s.mArray[i]);
}

只要确保你有正确的try/catch

【讨论】:

  • 我尝试这样做,但它给了我:Integer 类型中的方法 parseInt(String) 不适用于参数 (Array)
  • 试试Integer.parseInt(String.valueOf(mArray[i]))
【解决方案2】:
 return mArray[i] - s.mArray[i];   //FAIL HERE

至少你在这里失败是对的。

您说mArray 可以是任何类型(通用)。如果数组是原始类型,它应该可以工作。如果你的mArrayString 的数组,你就不能指望这条线工作。

也许你可以根据数组的数据类型来分解你的操作。

顺便说一句,如果您要“减去”两个字符串,您会期望什么? 这是一个伪代码(希望)为您指明正确的方向

if (test if your array is of type int){
  return mArray[i] - s.mArray[i];

}else if (test if your array is String){
  // do what you need...

} // ....whatever data type you expect

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-19
    • 2020-05-03
    • 2016-01-20
    • 2012-05-27
    • 1970-01-01
    相关资源
    最近更新 更多