Downcasting from Object to Integer Runtime Error: java.lang.ClassCastException
Run time exception-- java.lang.ClassCastingException
...
Integer intArr[] = new Integer[arrList.size()];
ArrayList <Integer> arrList =new ArrayList();
intArr=(Integer[])arrList.toArray(); // returns Object class which is downcaste to Integer;
I understand down-casting is not sa开发者_Python百科fe but why is this happening?
I also tried to converting ArrayList
to String
to Integer
to int
, but I get the same error.
Try to do this
intArr = arrList.toArray(new Integer[arrList.size()]);
What you get is a typed Integer
Array and not a Object array.
First of all, this doesn't bind the ArrayList to type Integer
.
ArrayList <Integer> arrList =new ArrayList();
Instead, this is what happens, arrList
is assigned to an ArrayList
of raw type, but that isn't a problem.
The problem lies in,
intArr=(Integer[])arrList.toArray();
since arrList
is a raw-type (due to the assignment, it gets assigned as new ArrayList<Object>()
by the compiler), you're effectively getting an Object[]
instead.
Try assigning arrList
to new ArrayList<Integer>()
and do this:
intArr = arrList.toArray(new Integer[arrList.size()]);
The problem here is that you are trying to convert an array of objects to an array of integers. Array is an object in itself and Integer[]
is not a sub-class of ArrayList
, nor vice versa. What you have to do in your case is cast individual items, something like this:
Integer intArr[] = new Integer[arrList.size()];
for(int i=0; i<intArr.length; i++)
{
intArr[i] = (Integer)arrList.get(i);
}
Naturally, you may get ClassCastException if individual elements in the array list are not of type Integer.
toArray(T[] a)
takes a paramter:
"a - the array into which the elements of the list are to be stored, if it is big enough; otherwise, a new array of the same runt"
精彩评论