简体   繁体   中英

How to convert object[] to specific type array

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?

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]);

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!

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];
}

@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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM