I am using this code to check that array is present in the HashMap
:
public class Test { public static void main(String[] arg) { HashMap<int[], String> map = new HashMap<int[], String>(); map.put(new int[]{1, 2}, "sun"); System.out.println(map.containsKey((new int[]{1, 2}))); } }
But this prints False
. How can I check that array is present in the HashMap
?
In a HashMap, keys and values can be added using the HashMap. put() method. We can also convert two arrays containing keys and values into a HashMap with respective keys and values.
Array Initialization in Java To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size: int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable.
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
The problem is because the two int[]
aren't equal.
System.out.println( (new int[] { 1, 2 }).equals(new int[] { 1, 2 }) ); // prints "false"
Map
and other Java Collections Framework classes defines its interface in terms of equals
. From Map API
:
Many methods in Collections Framework interfaces are defined in terms of the
equals
method. For example, the specification for thecontainsKey(Object key)
method says: "returnstrue
if and only if this map contains a mapping for a keyk
such that(key==null ? k==null : key.equals(k))
."
Note that they don't have to be the same object; they just have to be equals
. Arrays in Java extends from Object
, whose default implementation of equals
returns true only on object identity; hence why it prints false
in above snippet.
You can solve your problem in one of many ways:
equals
uses java.util.Arrays
equals/deepEquals
method. @Override equals(Object)
, you must also @Override hashCode
List<Integer>
that does define equals
in terms of the values they containequals
, you can just stick with what you have. Just as you shouldn't expect the above snippet to ever print true
, you shouldn't ever expect to be able to find your arrays by its values alone; you must hang-on to and use the original references every time.Object.equals
and Object.hashCode
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With