• Post Reply Bookmark Topic Watch Topic
  • New Topic

HashMap Initialization  RSS feed

 
Armando Moncada
Ranch Hand
Posts: 30
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not even sure if the term Initialization is correct for what I am doing, someone please correct me.

I have Intialized a HashMap two different ways and both seem to work but I have a question.



Then there is:


The question: Why does the Integer have to be "new" but the word "one" does not?
 
jatan bhavsar
Ranch Hand
Posts: 299
Eclipse IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Armando,

With the following line you are not creating a new String object in the heap but reusing a string literal .
String str = "one";

This will search in the string pool whether there is already object exist with the value one or not.. If it find the value then jvm simly assigns the reference but if jvm dont find it will create new object in string pool. There is a concept of string pool which you need to refer.

While if you are creating string object with
String str = new String("one") , it will create a new object for str dosent matter if the string pool contains the value one.

So you need to read the concept of string pool first to understand this. And for integer you need to create object with Integer before java 5 Integer i = 5 used to give error but now its working as autoboxing is there.

Please try to get idea from this example:



Try to do same for the String as well.
Regards
Jatan
 
Paul Clapham
Sheriff
Posts: 22844
43
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And since we have autoboxing (as jatan says) you could write this too:

 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You would be better to parameterise the Map Map<String, Integer> numberMap = new HashMap<String, Integer>();
That way the compiler will know you intend to use Strings and Integers, and as Paul C told you, use boxing.
you should avoid new Integer(1), too. Use Integer.valueOf(1) instead. Tthere is a similar String.valueOf(Object) method.
 
Armando Moncada
Ranch Hand
Posts: 30
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you all, for your invaluable help.
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You’re welcome
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!