mcacorner
mcacorner

Reputation: 1274

Java: Good candidate for key to use with HashMap

I have declared following HashMap

Map<Integer,String> map = new HashMap<>(); // Java 6+

I have two questions :
A) Is there any Issue(Performance or Other) , while I put element in HashMap with primitive data type for above declare HashMap for example

map.put(1,"abc");

Or I have to use only

map.put(new Integer(1),"abc");

B) Which is good candidate for HashMap if I have number(int) as a Key
String OR Integer

Upvotes: 1

Views: 1250

Answers (4)

Ashish
Ashish

Reputation: 520

When you are using the map.put(1,"abc");, the java compiler internally uses the Integer.valueOf(8) method

As for the performance question, I suggest you refer to String as key in hashmap

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172378

I think you can use any one but the important thing is key should preferably not be mutable as this can cause aberrant behavior.

Java HashMap relies on two things:

  • the hashCode() method, which returns an integer that is generated from the key and used inside the map
  • the equals(..) method, which should be consistent to the hash calculated, this means that if two keys has the same hashcode than it is desiderable that they are the same element.

So if you are planning to use just simple types as keys (like you said integers or strings) just don't worry, there's no difference. In both cases two different items will have the same hashcode.

Upvotes: 1

Siddhartha
Siddhartha

Reputation: 4444

You should use

Integer.valueOf(1)

instead of using the new keyword. Java stores values -128 thru 127 in a IntegerCache, and will return the already allocated value from the heap.

As for primitive v/s Integer object, java internally autoboxes both ways, so it will not make a difference.

Upvotes: 2

rmuller
rmuller

Reputation: 12849

This is effectively the same. Java is using auto boxing to convert

map.put(1,"abc");

to

map.put(Integer.valueOf(1),"abc");

during compile time.

If you need better performace, look at external libraries supporting primivites as key in maps.

Upvotes: 1

Related Questions