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!!

1
  • Check out the Object#toString() method. Commented Dec 22, 2013 at 18:03

3 Answers 3

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()));
Sign up to request clarification or add additional context in comments.

2 Comments

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 When I said array that mean me.getValue() :)
2

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

2 Comments

Arrays.toString() does not work for objects... me.getValue() is an object
@Mohit you could use generics so Arrays.toString() will recieve String[]
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();
}

2 Comments

at String[] value = me.getValue(); it gives an error "cannot convert objects into strings"
@Mohit: Thanks for pointing that out, fixed now. I just forgot to cast.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.