Why int[] Array is not reliable as Java HashMap Key

18 hours ago 1
ARTICLE AD BOX

Let's take it step by step. Yes, you can use an array as a key... even if it doesn't make any sense.
Let's look at the “why?” with an example:

Integer a[] = { 1, 2 }; Integer b[] = { 1, 2 }; System.out.println( a.equals( b ) );

The previous statement prints "false", as you have been told in the comments (even the false “AI”, which I would not ask anything), the class “[]” does not override the equals() method, so it only verifies that it is the same object (that the pointer points to the same place in memory).
This may not seem like a big problem, since if I use the same array to create the entry and get the value, it should work, and in fact it does:

Map <int[], String> mp = new HashMap<>(); int keyA[] = new int[] { 1, 2 }; mp.put( keyA, "Work" ); System.out.println( mp.get( keyA ));

Very nice, he even printed “Work”, everything seems fine, but...

Map <int[], String> mp = new HashMap<>(); int keyA[] = new int[] { 1, 2 }; int keyB[] = new int[] { 1, 2 }; mp.put( keyA, "Work" ); if( mp.get( keyB ) == null ) System.out.println( "Not work" );

And it does indeed print “Not work”, here we confirm that two arrays with the same content are not interchangeable as "key", but we haven't seen the worst yet...

Map <int[], String> mp = new HashMap<>(); int keyA[] = new int[] { 1,2 }; int keyB[] = new int[] { 1,2 }; mp.put( keyA, "Work" ); keyA[ 0 ] = 14; System.out.println( mp.get( keyA ));

How awful! We have modified the contents of the array, and it keeps printing “Work”...

Conclusion: Although you can use them... don't, and if you decide to use them anyway, don't waste resources loading values into them; an empty array works exactly the same.

Map <int[], String> mp = new HashMap<>(); int keyA[] = new int[2]; int keyB[] = new int[2]; mp.put( keyA, "Work" ); System.out.println( mp.get( keyA )); if( mp.get( keyB ) == null ) System.out.println( "Not work" ); }
Read Entire Article