-1

I am facing problem in getting value from hashmap

Map<String, Object> mapObj = new HashMap<String, Object>();
String[] strArray = {"String1", "String2"};
mapObj.put("string_array",strArray);

//trying to print:
for (String entry : mapObj.keySet()) {
    Log.v("", "map entry "+ entry);
    Log.v("", "map value "+ mapObj.get(entry));
}

actual output: [Ljava.lang.String;@410ee550

expected : String1 String2

androidraj
  • 85
  • 2
  • 7

5 Answers5

2

Array types don't override Object#toString so what you see is the super class representation

getClass().getName() + '@' + Integer.toHexString(hashCode())

of the array object itself. You could do

System.out.println("map value "+ Arrays.toString((String[])mapObj.get(entry)));

Note: better to use a Map<String, String[]> in place of the original collection type to avoid casting.

Reimeus
  • 158,255
  • 15
  • 216
  • 276
0

You are getting an array Object. You should iterate over that object to get elements in it.

for (String entry : mapObj.keySet()) {
        String[] arr = (String[]) mapObj.get(entry);
        for (String string : arr) {
            System.out.println(string);
        }
    }}
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

You need typecaste here

for (String entry : mapObj.keySet()) {
    Log.v("", "map entry "+ entry);
    Log.v("", "map value "+ mapObj.get(entry));
  String[] strArray = (String[])mapObj.get(entry);

 //now iterate strArray 
}
PSR
  • 39,804
  • 41
  • 111
  • 151
0

Since you added String[] into the map so you will get String[]from the map. Therefore you need to cast the retrieved object. (String[])mapObj.get(entry);

Your actual output clearly suggest that Map returned an String[]. See this for explanation about [Ljava.lang.String;

Since String[] don't override toString(), hence you need to fetch each element in array like:

String[] arr = (String[])mapObj.get(entry);
for(String eachString: arr){
  System.out.print(eachString);
}
Community
  • 1
  • 1
Gaurav Gupta
  • 4,586
  • 4
  • 39
  • 72
0

To make it simple you can use Arrays.toString method

public class MapValue {

    public static void main(String[] args) {
        Map<String, Object> mapObj = new HashMap<String, Object>();
        String[] strArray = {"String1", "String2"};
        mapObj.put("string_array",strArray);

        //trying to print:
        for (String entry : mapObj.keySet()) {
            Log.v("", "map entry "+ entry);
            Log.v("", "map value "+ Arrays.toString((Object[]) mapObj.get(entry)));
        }

    }

}
Syam S
  • 8,421
  • 1
  • 26
  • 36