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 safe but why is this happening?
I also tried to converting ArrayList to String to Integer to int, but I get the same error.
First of all, this doesn’t bind the ArrayList to type
Integer.Instead, this is what happens,
arrListis assigned to anArrayListof raw type, but that isn’t a problem.The problem lies in,
since
arrListis a raw-type (due to the assignment, it gets assigned asnew ArrayList<Object>()by the compiler), you’re effectively getting anObject[]instead.Try assigning
arrListtonew ArrayList<Integer>()and do this: