0
HashMap<String, int[]> H = new HashMap<String, int[]>(); 
H.put("drdetroit", new int[]{1,2});
H.put("drdetroit", new int[]{1,3}); 
System.out.println(H.get("drdetroit").toString());

It prints out

[I@c3c749

I assume this is the hashed value(is it?). How can I make it print my actual values?

9
  • If you want to print the values of an array using toString() on that array, you will get something completely different from the values, it does not matter if it is in a HashMap or not. Use Arrays.toString(array) instead
    – andreih
    Dec 5, 2012 at 10:06
  • Also your hashmap will only print the first value so don't get confused. :) Dec 5, 2012 at 10:08
  • @limelights: How can I make it print both of them= Dec 5, 2012 at 10:09
  • You have to change the second key to something unique since HashMaps stores only unique keys. So H.put('drdetroit', value); and H.put('drchicago', value); will work for you Dec 5, 2012 at 10:10
  • 1
    Nah, but you can do a map with a list. So HashMap<String, List<int[]>> H = new HashMap<String, List<int[]>>(); and then add the values to the list. I'll post an answer for you to see. Dec 5, 2012 at 10:12

5 Answers 5

2

This is what you're after I believe. Since a HashMap can only store unique keys you're forced to go with a list if you want multiple values for one (1) key.

There are perhaps better ways of achieving this but it's working and is pretty expressive in itself and pretty clear what it does and how.

The HashMap now accepts the List interface and can thusly accept any list-type that implements it. Which is pretty neat! :)

ArrayList<int[]> values = new ArrayList<int[]>();

values.add(new int[]{1,2});
values.add(new int[]{1,3});

HashMap<String, List<int[]>> H = new HashMap<String, List<int[]>>(); 

H.put("drdetroit", values);

for(String key : H.keySet()) {
    for(int[] array : H.get(key)){
        System.out.println(Arrays.toString(array));
    }
}
2

You use Arrays.toString(H.get("drdetroit"));

6
1
System.out.println(Arrays.toString(H.get("drdetroit")));

I - stands for int array and c3c749 is hashcode

3
0

Because you try to make a String out of an array!

You could do for example:

String myArray = H.get("drdetroit");
System.out.println(myArray[0]);
1
  • Mm, no, he just prints it's object value.
    – Shark
    Dec 5, 2012 at 10:06
0

Try this to print array values -

System.out.println(Arrays.toString(H.get("drdetroit")));

H.get("drdetroit").toString() returns array class name and @ and hashcode in hexString.

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.