Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast primitive type array into object array in java

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.

like image 350
aumanets Avatar asked Apr 09 '11 16:04

aumanets


People also ask

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

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.

Can we assign Integer array to object array?

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

How do you convert a primitive type array to a wrapper class?

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.

How do you cast an array to an object?

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.


1 Answers

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; 
like image 71
Datageek Avatar answered Sep 22 '22 19:09

Datageek