Cast primitive type array into object array in java Cast primitive type array into object array in java arrays arrays

Cast primitive type array into object array in java


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;


In Java, primitive types and reference types are two distinct worlds. This reflects to arrays: A primitive array is not an object array, that's why you can't cast.

Here is a simpler version of your solution in the question:

private Object[] getArray(Object val){    if (val instanceof Object[])       return (Object[])val;    int arrlength = Array.getLength(val);    Object[] outputArray = new Object[arrlength];    for(int i = 0; i < arrlength; ++i){       outputArray[i] = Array.get(val, i);    }    return outputArray;}

This will still work when they sometimes decide to add new primitive types to the VM.

Of course, you might want to do the copying always, not only in the primitive case, then it gets even simpler:

private Object[] getArray(Object val){    int arrlength = Array.getLength(val);    Object[] outputArray = new Object[arrlength];    for(int i = 0; i < arrlength; ++i){       outputArray[i] = Array.get(val, i);    }    return outputArray;}

Of course, this is not casting, but converting.


Primitive type cannot be transformed in this way.In your case, there is an array of double values, cause of 3.14.This will work:

    List<Object> objectList = new ArrayList<Object>();    objectList.addAll(Arrays.asList(0,1,2,3.14,4));

Even this works :

List<Object> objectList = new ArrayList<Object>();objectList.addAll(Arrays.asList(0,"sfsd",2,3.14,new Regexp("Test")));for(Object object:objectList){    System.out.println(object);}

UPDATEOk, there as there was said, there is not direct way to cast a primitive array to an Object[]. If you want a method that transforms any array in String, I can suggest this way

public class CastArray {    public static void main(String[] args) {        CastArray test = new CastArray();        test.TestObj(new int[]{1, 2, 4});        test.TestObj(new char[]{'c', 'a', 'a'});        test.TestObj(new String[]{"fdsa", "fdafds"});    }    public void TestObj(Object obj) {        if (!(obj instanceof Object[])) {            if (obj instanceof int[]) {                for (int i : (int[]) obj) {                    System.out.print(i + " ");                }                System.out.println("");            }            if (obj instanceof char[]) {                for (char c : (char[]) obj) {                    System.out.print(c + " ");                }                System.out.println("");            }            //and so on, for every primitive type.        } else {            System.out.println(Arrays.asList((Object[]) obj));        }    }}

Yes, it's annoying to write a loop for every primitive type, but there is no other way, IMHO.