Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I need convert HashMap to a String array, follow is my java code

import java.util.HashMap;
import java.util.Map;

public class demo {

    public static void main(String[] args) {

        Map<String, String> map1 = new HashMap<String, String>();

        map1.put("1", "1");
        map1.put("2", "2");
        map1.put("3", "3");

        String[] str = (String[]) map1.keySet().toArray();

        for(int i=0; i<str.length;i++) {
            System.out.println(str[i]);
        }
    }
}

when i run the code, but it shows

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
at demo.main(demo.java:17)

i am confused with this,who can help me.

share|improve this question
up vote 15 down vote accepted

toArray() returns an Object[], regardless of generics. You could instead use the overloaded variant:

String[] str = map1.keySet().toArray(new String[map1.size()]);

Alternatively, since a Set's toArray method gives no gaurentee about the order, and all you're using the array for is printing out the values, you could iterate the keySet() directly:

for (String str: map1.keySet()) {
    System.out.println(str);
}
share|improve this answer
1  
String[] str = map1.keySet().toArray(new String[map1.size()]); you missed the parenthesis in map1.size() – ir2pid Apr 22 '15 at 20:14
    
@ir2pid - indeed, thanks for noticing! Fixed. – Mureinik Apr 23 '15 at 6:03

It is returning Object[] Not String[]. Try this:

Object[] obj = (Object[]) map1.keySet().toArray();
for(int i=0; i<obj.length;i++) {
    String someString = (String)obj[i];
    System.out.println(someString);
}
share|improve this answer
2  
And you cast Object[] to Object[] at the first line? – farukdgn Oct 3 '15 at 17:31
    
Indeed two casts (i.e. Object[] and String) cannot be done in one step. They need to be done step by step. Thanks for the great incite. – Ahmed Akhtar Apr 25 at 7:25

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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