Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>the int[] array objects have no way of knowing if two arrays are equal because they are in effect just pointers, and since they are pointing to two different arrays, they are considered unequal. The reason why the pointers are used to compare equality is because the Object class defines the most rudimentary equals method in such a fashion.</p> <p>You need to create a simple class to encapsulate your array. Here is a simple one anyone could understand.</p> <pre><code>class IntArray { int[] myArray; public IntArray () { myArray = new int[0]; } public IntArray (int [] array) { myArray = array; } /** * This method is for accessing the array. * The array CAN be modified using this method. */ public int[] getArray() { return myArray; } /** * Uses built-in hashCode generating method * within the Arrays class. * Importing java.util.Arrays is necessary. */ public int hashCode() { return Arrays.hashCode(myArray); } public boolean equals(Object o) { if (!(o instanceof IntArray)) return false; //Should use Arrays.equals(o.myArray, myArray); if (o.myArray.length != myArray.length) return false; else { for (int i = 0; i &lt; myArray.length; i++) { if (myArray[i] != o.myArray[i]) { return false; } } return true; } } } </code></pre> <p>Once this is done, you can easily do something like you have done before:</p> <pre><code> Stack&lt;In&gt; myStack = new Stack&lt;int[]&gt;(); myStack.push( new IntArray (new int[]{1,2}) ); myStack.push( new IntArray (new int[]{1,3}) ); myStack.push( new IntArray (new int[]{1,4}) ); if (myStack.contains( new IntArray (new int[]{1,3})) ) { System.out.println("YES"); } else { System.out.println("NO"); } </code></pre> <p>That should definitely work.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload