eXXXXXXXXXXX2
eXXXXXXXXXXX2

Reputation: 1580

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?

Upvotes: 19

Views: 9684

Answers (4)

Kuldeep Jain
Kuldeep Jain

Reputation: 8598

Use this code for listing out the values of map i.e. class names:

Object[] array = map.values().toArray();
for (Object object : array) {
    System.out.println(object.toString());
}

Upvotes: 0

dacwe
dacwe

Reputation: 43504

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().

Upvotes: 37

Pablo
Pablo

Reputation: 3673

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

Upvotes: 1

amit
amit

Reputation: 178521

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.

Upvotes: 4

Related Questions