Collection.toArray() java.lang.ClassCastException

前端 未结 4 889
既然无缘
既然无缘 2021-02-05 08:23
import java.util.HashMap;
import java.util.Map;


public class Main
{
    public static void main(String[] args)
    {
        Map map=new HashMap&l         


        
4条回答
  •  Happy的楠姐
    2021-02-05 09:06

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

提交回复
热议问题