Search code examples
javaarraysstackcontains

How can I wrap the int[] into an object and implement equals()?


I am trying to see how can I test if an element, with the same value as one already inside my Stack, is in fact in my stack.

ex.

int aa[] = {5,1};
int bb[] = {3,4};
int cc[] = {3,4};

Stack stack = new Stack();

stack.push(aa);
stack.push(bb);

System.out.println(stack.contains(cc));
>>>false

If I understand correctly this is false because the int[] objects are pointers, and becuase they are pointing at two different arrays, they are considered unequal. (From this answer)

I'm trying to wrap the int[] into an object and implement equals and hashCode, as was done in the answer to the other question but I'm getting a Cannot resolve symbol 'myArray' on o.myArray.length != myArray.length and int i = 0; i < o.myArray.length; i++. I also don't undertand why I need / where hashCode() is used.

Can someone tell me what I'm doing wrong or if there is a better solution?

import java.util.Arrays;

public class IntArray {

    public int[] myArray;

    public IntArray () {
        myArray = new int[0];
    }

    public IntArray (int[] array) {
        myArray = array;
    }

    public int[] getArray() {
        return myArray;
    }

    public int hashCode() {
        return Arrays.hashCode(myArray);
    }

    public boolean equals(Object o) {

        if (!(o instanceof IntArray))
            return false;

        if (o.myArray.length != myArray.length)
            return false;
        else {
            for (int i = 0; i < o.myArray.length; i++) {
                if (myArray[i] != myArray[i]) {
                    return false;
                }
            }
            return true;
        }
    }
}

Solution

  • I shall leave the question of a better way of doing this and explain what you are being told.

    o is always of type Object in the equals method. The Object class does not have a myArray field - hence the error. That you checked o's an instance of IntArray previously using instanceof and that o must be at least an IntArray due to that and it defines a myArray field is not enough - you are required to cast it explictly:

    ((IntArray)o).myArray.length;
    IntArray a = (IntArray)o;
    a.myArray.length;
    

    So basically that's it as far as that goes - you are not being explicit. I would have expected any syntax checking editor to have picked that up really so if that is approriate consider getting any one of the myriad available to avoid such mistakes.