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?
toArray() returns an Object[], it can be converted to String array by passing the String[] as parameter.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With