Reputation: 355
In the code below an integer array is assigned to an object. If that's possible, why can't i access them through obj? The code compiles, but i get a ClassCastException, I have tried casting the object to String, i get the same error
public class test
{ public static void main(String ab[])
{
Object obj = new int[] {1,2,3,4,5,6,7,8,9,10};
Integer[] i = (Integer[]) obj;
for( Integer c : i)
System.out.println(c);
}
}
Upvotes: 1
Views: 788
Reputation: 297
It is because you are trying to cast an object of type int[] to an object of type Integer[], that is not possible, although an Integer class can hold int types and in later versions of java you can even assign an int to an Integer like this:
Integer a = 2;
they are different.
If you are using java 5 or above you can do something like this:
public class test
{ public static void main(String ab[])
{
Object obj = new Integer[] {1,2,3,4,5,6,7,8,9,10};
Integer[] i = (Integer[]) obj;
for( Integer c : i)
System.out.println(c);
}
}
Upvotes: 1
Reputation: 40336
An int[]
is not the same as an Integer[]
.
You create an int[]
:
Object obj = new int[] {1,2,3,4,5,6,7,8,9,10};
But then you attempt to cast it back to an Integer[]
, which you cannot do, because it is an int[]
. int[]
and Integer[]
are both Object
, but you cannot cast between the two like that, for the same reason that, e.g., this does not work:
Object obj = new String("");
File f = (File)obj; // obj is a String, will throw ClassCastException
Instead, either create an Integer[]
to begin with:
Object obj = new Integer[] {1,2,3,4,5,6,7,8,9,10};
Integer[] i = (Integer[]) obj;
Or use an int[]
:
Object obj = new int[] {1,2,3,4,5,6,7,8,9,10};
int[] i = (int[]) obj;
The same is true of your attempt to cast an int[]
to a String
. You can't convert things just by casting them around in Java.
Upvotes: 2