Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection.toArray() java.lang.ClassCastException

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


public class Main
{
    public static void main(String[] args)
    {
        Map<Integer,Class> map=new HashMap<Integer,Class>();
        map.put(0,Main.class);
        Class[] classes=(Class[])map.values().toArray();
        for (Class c:classes)
            System.out.println(c.getName());
    }

}

I try cast in this line Class[] classes=(Class[])map.values().toArray(); but get exception.

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Class; at Main.main(Main.java:11)

What is problem?

like image 301
eXXXXXXXXXXX2 Avatar asked Feb 15 '12 12:02

eXXXXXXXXXXX2


People also ask

What is the use of toArray () in Java?

The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order.

What is Java lang ClassCastException?

Class ClassCastExceptionThrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException : Object x = new Integer(0); System. out. println((String)x);

What causes ClassCastException in Java?

Introduction. 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.


3 Answers

Change:

Class[] classes = (Class[]) map.values().toArray();

To:

Class[] classes = map.values().toArray(new Class[0]);

This gives information on which type of array to convert the Collection to. Otherwise, it returns an array of type Object (and that cannot be cast to an Class[]).


Quoted from the API documentation for Collection.toArray(T[] a):

Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. ...
Note that toArray(new Object[0]) is identical in function to toArray().

like image 53
dacwe Avatar answered Oct 19 '22 23:10

dacwe


toArray() returns an Object[] [and not any object derived from Object[]]. Each element in this array is of type Class, but the array itself is not of type Class[]

You should cast each element in the array to Class instead of trying to cast the array, or use Collection.toArray(T[]) to avoid casting.

like image 29
amit Avatar answered Oct 19 '22 22:10

amit


Use T[] toArray(T[] a) from Collection instead.

like image 30
Pablo Avatar answered Oct 19 '22 22:10

Pablo