2
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 ?

4
  • List<Integer> list=new ArrayList<Integer>();why "list.toArray() " is an Object array???? Commented Mar 28, 2015 at 8:58
  • you might want to take a look at this link stackoverflow.com/questions/1115230/… Commented Mar 28, 2015 at 9:03
  • There is no automatic recursive cast to cast Arrays of type A to type B. You have to do that manually or by using dedicated methods like 'Arrays.Copyof()'. Commented Mar 28, 2015 at 9:08
  • ”you can't treat a list of Integer IS-A list of Object “ thanks tom!thanks toni! Commented Mar 28, 2015 at 9:23

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.