What's wrong with the following code?
Object[] a = new Object[1];
Integer b=1;
a[0]=b;
Integer[] c = (Integer[]) a;
The code has the following error at the last line :
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
Ross, you can use Arrays.copyof() or Arrays.copyOfRange() too.
Integer[] integerArray = Arrays.copyOf(a, a.length, Integer[].class);
Integer[] integerArray = Arrays.copyOfRange(a, 0, a.length, Integer[].class);
Here the reason to hitting an ClassCastException
is you can't treat an array of Integer
as an array of Object
. Integer[]
is a subtype of Object[]
but Object[]
is not a Integer[]
.
And the following also will not give an ClassCastException
.
Object[] a = new Integer[1];
Integer b=1;
a[0]=b;
Integer[] c = (Integer[]) a;
You can't cast an Object
array to an Integer
array. You have to loop through all elements of a and cast each one individually.
Object[] a = new Object[1];
Integer b=1;
a[0]=b;
Integer[] c = new Integer[a.length];
for(int i = 0; i < a.length; i++)
{
c[i] = (Integer) a[i];
}
Edit: I believe the rationale behind this restriction is that when casting, the JVM wants to ensure type-safety at runtime. Since an array of Objects
can be anything besides Integers
, the JVM would have to do what the above code is doing anyway (look at each element individually). The language designers decided they didn't want the JVM to do that (I'm not sure why, but I'm sure it's a good reason).
However, you can cast a subtype array to a supertype array (eg Integer[]
to Object[]
)!
Or do the following:
...
Integer[] integerArray = new Integer[integerList.size()];
integerList.toArray(integerArray);
return integerArray;
}
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
you try to cast an Array of Object to cast into Array of Integer. You cant do it. This type of downcast is not permitted.
You can make an array of Integer, and after that copy every value of the first array into second array.
instanceof
test should pass in order for the assignment to go through.
In your example it results
Object[] a = new Object[1]; boolean isIntegerArr = a instanceof Integer[]
sysout
of the above line, it would return false;
(Arrays.asList(a)).toArray(c);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.