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