0

I'm trying to create a hashmap which has a String key and stores an Integer array. While using hashmap.get() , I want to retrieve the stored array. I've used to following code:

HashMap hm = new HashMap();
String[] arr=new String[]{"-1","-1","-1","-1"};
hm.put("A", arr);
hm.put("B", arr);
hm.put("C", arr);
hm.put("E", arr);
Set set = hm.entrySet();
Iterator i = set.iterator();
while(i.hasNext()) 
{
    Map.Entry me = (Map.Entry)i.next();
    System.out.print(me.getKey() + ": ");
    System.out.println(me.getValue());
}

The output i'm getting is:

D: [Ljava.lang.String;@88d00c6
E: [Ljava.lang.String;@88d00c6
A: [Ljava.lang.String;@88d00c6
B: [Ljava.lang.String;@88d00c6
C: [Ljava.lang.String;@88d00c6

Can anyone please help!!

Asfab
  • 398
  • 6
  • 11
Mohit
  • 11
  • 1
  • 3

3 Answers3

3
 System.out.println(me.getValue());

That each value is an Array. When you print, by default Object#toString() method calls and result in that hex string.

Try to use the util method from Arrays class, to print array.

System.out.println(Arrays.toString(me.getValue()));
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • I actually have to print the data stored in the hashmap... the data that i retrieve from the map..Arrays.toString() does not work for objects... me.getValue() is an object – Mohit Dec 23 '13 at 13:22
  • @Mohit When I said array that mean me.getValue() :) – Suresh Atta Dec 23 '13 at 13:23
2

use Arrays.toString(me.getValue()); instead, default implementation of array Object's toString() doesn't return in pretty format

jmj
  • 237,923
  • 42
  • 401
  • 438
1

System.out.println uses the default toString method for arrays, which is ugly (some people claim it is the memory address of the array in the virtual machine). Instead, use a utility function or print the array's contents manually.

while(i.hasNext()) 
{
    Map.Entry me = (Map.Entry)i.next();
    System.out.print(me.getKey() + ": ");
    String[] value = (String[])me.getValue();
    for(String str:value)
    {
        System.out.println(str+"\t");
    }
    System.out.println();
}
Flight Odyssey
  • 2,267
  • 18
  • 25
  • at String[] value = me.getValue(); it gives an error "cannot convert objects into strings" – Mohit Dec 23 '13 at 13:18
  • @Mohit: Thanks for pointing that out, fixed now. I just forgot to [cast](http://stackoverflow.com/questions/5289393/casting-variables-in-java). – Flight Odyssey Dec 23 '13 at 15:12