Reputation: 21200
I do not think I can convert the following:
List<B> c = new ArrayList<B>();
c.add(***);
object[] a = c.toArray();
B[] b = (B[])a; //How to cast a back to B[]?
How can I achieve this in Java?
Upvotes: 7
Views: 8442
Reputation: 7678
@Jon Skeet's answer is correct but here is some context from the Intellij IDEA inspection info:
There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()])) or using an empty array (like c.toArray(new String[0]).
In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation.
Upvotes: 0
Reputation: 1500765
The other answers show what to do if you really need to convert an Object[]
- but there's a better approach. Change your code to start with:
List<B> c = new ArrayList<B>();
c.add(***);
B[] b = c.toArray(new B[c.size()]);
Or:
List<B> c = new ArrayList<B>();
c.add(***);
B[] b = c.toArray(new B[0]);
Upvotes: 10
Reputation: 32959
You cannot do this through a cast. You must copy the data.
B[] b = new B[a.length];
for (int i=0; i<a.length; i++){
b[i] = (B)a[i];
}
Upvotes: 1
Reputation: 298908
If every element of a
is of type B
, you have two options (if not, you need to explain what's going on first):
B[] bArray;
if(a instanceof B[]){
// a is actually of type B[], so we'll cast it
bArray = (B[]) a;
}else{
// a is of type Object[], so we'll create a new array and copy the values
bArray = Array.newInstance(B.class, a.length);
System.arraycopy(a, 0, bArray, 0, a.length);
}
Also, this will only work if B is a real type, not a generic parameter!
Upvotes: 4