Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

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, I get the following ClassCastException.

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
at demo.main(demo.java:17)
like image 670
JackSun Avatar asked Mar 29 '14 13:03

JackSun


People also ask

How do I resolve Java Lang ClassCastException error?

To prevent the ClassCastException exception, one should be careful when casting objects to a specific class or interface and ensure that the target type is a child of the source type, and that the actual object is an instance of that type.

What is Java Lang ClassCastException?

ClassCastException is a runtime exception raised in Java when we try to improperly cast a class from one type to another. It's thrown to indicate that the code has attempted to cast an object to a related class, but of which it is not an instance.

What is Ljava Lang String?

Ljava.lang.String stands for the string class (L followed by class/interface name) Few Examples: Class. forName("[D") -> Array of primitive double. Class.


3 Answers

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

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

Alternatively, since a Set's toArray method gives no guarantee 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);
}

EDIT: Just to complete the picture, in Java 8, the foreach method can be used to make the code more elegant:

map1.keySet().forEach(System.out::println);
like image 54
Mureinik Avatar answered Oct 19 '22 17:10

Mureinik


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);
}
like image 6
Sabuj Hassan Avatar answered Oct 19 '22 15:10

Sabuj Hassan


toArray()method is defined in List interface so every where there is an instance of List, you also have access to this method.

At first you might think that you can cast an array of Objects which its elements are all of type String to a String array but java specs says otherwise Link, in short it says:

bArr = new B[]; A[] aArr = (A[]) bArr;

"works" at runtime if and only if B is a subtype of A (or A itself). Whether B actually only contains As is irrelevant and the compile-time type of bArr is not used either (what matters is the runtime type):

In your code by calling : image_urls.toArray() you will get an array of Object and since Object is not SubType of String, you get exception. To do this write, use other overload of toArray() which gets an array of certain type (for type reference) as "Mureinik" mentioned.

like image 2
Mr.Q Avatar answered Oct 19 '22 16:10

Mr.Q