How to convert object[] to specific type array
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!