I'm not sure if this is what you needed but here is your code that I modified:
Map<String, String[]> map = new HashMap<String, String[]>();
map.put("key1", new String[]{"value1", "test1"});
map.put("key2", new String[]{"value2"});
Object[] keys = map.keySet().toArray();
Object[] values = map.values().toArray();
System.out.println("key = " + keys[0] + ", value #1 = " + ((Object[])values[0])[0]);
System.out.println("key = " + keys[1] + ", value #1 = " + ((Object[])values[1])[0] + ", value #2 = " + ((Object[])values[1])[1]);
Output:
key = key2, value #1 = value2
key = key1, value #1 = value1, value #2 = test1
Note that under key[0]
you have "key2"
instead of "key1"
. That is because HashMap
doesn't keep the keys in the same order you add them. To change that you must choose another Map
implementation (for example TreeMap
if you want to have alphabetical order).
How this works? Java allows you to cast arrays to Object
. toArray()
method returns Object[]
- an array of Objects
, but those objects are also arrays (of String - as you defined in your map)! If you print just value[0]
it would be like printing mySampleArray
where mySampleArray
is:
Object[] mySampleArray = new Object[5];
So you call it on the whole array not an element. This is why you get [Ljava.lang.String;@7c6768
etc. (which is className@HashCode - thats what default toString()
method does).
In order to get to your element you have to go deeper.
((Object[])values[0])[0]
This means: Take values[0] (we know it holds an array), cast it to array and take first element.
I hope this helps, please let me know if you need any additional info.