Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Extract HashMap array value

 
Adrian Airmil
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The value in the hashmap is an array and i wish to get that array to loop through it.



However result in the browser is:

Would appreciate if someone could point out whats wrong in that code. Thanks
 
Anupam Sinha
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use generics (if JDK 1.5 or higher) to specify at compile time what would the collection be storing. Else cast the value to a String array and use it.
 
Jaime M. Tovar
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The String array is an object by its own. When you ask in the hashmap for the value of the key you get the array object. Try to wrap the array so it will print in a clean way. You can use the array to create a structure that will make it easier to handle the data. Something like a Collection or alike.
 
gkumar kumar
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Extract array from hashmap for the example you mentioned, code is as follows

HashMap hmap=new HashMap();
hmap.put("storeKey", new String[]{"first","second"});
String obj[]=(String[])hmap.get("storeKey");

for(int i=0;i<obj.length;i++){
System.out.println(obj[i]);
}
 
Adrian Airmil
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks everyone. Wrapping it made it work.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic