Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert object[] to specific type array

Tags:

java

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?

like image 319
user705414 Avatar asked Sep 21 '11 10:09

user705414


People also ask

Can we convert object to array in Java?

toArray() returns an Object[], it can be converted to String array by passing the String[] as parameter.

How do you convert an object to an array of key value pairs in TypeScript?

Object. entries() method is used to return an array consisting of enumerable property [key, value] pairs of the object which are passed as the parameter.

How do you convert an object to an array in Python?

Using numpy.asarray() , and true (by default) in the case of np. array() . This means that np. array() will make a copy of the object (by default) and convert that to an array, while np.


2 Answers

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]);
like image 157
Jon Skeet Avatar answered Oct 14 '22 19:10

Jon Skeet


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!

like image 30
Sean Patrick Floyd Avatar answered Oct 14 '22 19:10

Sean Patrick Floyd