Why I cannot do this in java?
Object[] o = (Object[])(new int[]{0,1,2,3.14,4});
I have a method that receives an object and then represents it as a string, but depending on his type (primitive, primitive wrapper, array, etc...). When I was creating a Unit test, I was passing an array as Object which is Ok, but when I perform cast of that object into Object[] I'm getting ClassCastException. This is only happening with primitive type arrays. Is there any way to avoid this behavior? If not, could someone explain what is the reason of this behavior on Java Virtual Machine.
Any help is very appreciated.
Converting an array to Set object The Arrays class of the java. util package provides a method known as asList(). This method accepts an array as an argument and, returns a List object. Use this method to convert an array to Set.
You can't call . intValue() on an Object , as the Object class lacks the method intValue() . Instead, you need to cast the Object to the Integer class first, like so: newarray[e] = ((Integer)array[i]).
Convert by Looping First, we will convert an array of primitive types to an array of wrapper objects. To do that, we will simply iterate through the primitive array and use autoboxing to convert each element to the respective wrapper object type.
To convert an array to an object, use the reduce() method to iterate over the array, passing it an object as the initial value. On each iteration, assign a new key-value pair to the accumulated object and return the result. Copied! const arr = ['zero', 'one', 'two']; const obj4 = arr.
Here is a simple one-liner:
Double[] objects = ArrayUtils.toObject(primitives);
You will need to import Apache commons-lang3:
import org.apache.commons.lang3.ArrayUtils;
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