-3
/**
 * 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();
}

Error: The operator - is undefined for the argument type(s) Array<T>, Array. Can someone please tell me how do I return the difference between the 2 arrays element?

Thank you.

chris
  • 4,840
  • 5
  • 35
  • 66
nurul
  • 1

2 Answers2

-1

You could try doing an Integer.parseInt(), if you're certain the array element is an int. Similarly, you could also force a cast.

Method A:

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

Method B:

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

Just make sure you have the proper try/catch in place.

domdomcodecode
  • 2,355
  • 4
  • 19
  • 27
-1
 return mArray[i] - s.mArray[i];   //FAIL HERE

At least you are right about failing here.

You said that mArray could be any type (Generic). It should work if the array is a primitive type. You can't expect this line to work if your mArray is an array of String.

maybe you can break your operation down depending on which data type the array has.

btw, what would you expect if you are "Subtracting" two Strings? here's a pseudocode to (hopefully) point you in the right direction

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
jmcg
  • 1,547
  • 17
  • 22