码迷,mamicode.com
首页 > 编程语言 > 详细

Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;

时间:2015-03-29 15:10:14      阅读:276      评论:0      收藏:0      [点我收藏+]

标签:java   cast   

public class Test {

    public static void main(String[] args) {
        System.out.println(new CountingGenerator.String(12).next());
        List<Integer> list=new ArrayList<Integer>();
        list.add(new Integer(1));
        list.add(new Integer(2));

        Integer[] c = {1,3,3};
        //throw an exception:
        c = (Integer[]) list.toArray();
    }
}

I wonder why this happened ? Integer is a subclass of Object,so it should be Ok instead! please answer me deeply! I want know why? what‘s the principle ?



回答:

Change the line

 c=(Integer[]) list.toArray();

to

c= list.toArray(c); // add c as parameter

In your list.toArray(); returns Object[] and JVM doesn‘t know how to blindly downcast Object[]to Integer[].

public Object[] toArray()      //return Object type array
public <T> T[] 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

Java Docs

shareedit
you can‘t treat a list of Integer IS-A list of Object!

Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;

标签:java   cast   

原文地址:http://blog.csdn.net/lemon89/article/details/44727013

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!