Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java Puzzler on Arrays

DZone's Guide to

Java Puzzler on Arrays

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

Today, while working with arrays I came accross a Java puzzle which made me wonder WHY IS THIS PIECE OF CODE NOT WORKING?

Java Puzzle

Can you guess whether this Junit test case will pass?

@Test
public void testMapOfArray() {

Map<String[], String[]> map = new HashMap<String[], String[]>();
map.put(new String[] { "shekhar" },
new String[] { "I am Java Developer" });
map.put(new String[] { "rahul" }, new String[] { "I am C# Developer" });

String[] description = map.get(new String[] { "shekhar" });
assertThat(description[0], IsEqual.equalTo("I am Java Developer"));
}


Everytime I ran this test it failed with NullPointerException.

What's the reason for this unexpected behavior?

The problem is that String[] uses object identity for equals and hashcode methodsz. So,

String[] arr1 = new String[] { "shekhar" };
String[] arr2 = new String[] { "shekhar" };

 will not match with eachother in a HashMap. 

Advice
Don't use arrays as HashMap keys. If you want to use an array as a key, then write a wrapper arround an array and override equals and the hashcode method.

 

 

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}