简体   繁体   中英

casting integer array to object array in java

I am using JDK 1.6 but the second line in the following snippet gives a compile error in Eclipse:

long[] css = new long[]{1, 2, 3};
Object[] objs = Arrays.copyOf(ccs, ccs.length, Object[].class );

Error is: The method copyOf(long[], int) in the type Arrays is not applicable for the arguments (long[], int, Class)

Casting is required for

org.hibernate.criterion.Restrictions.in("PropertyName", objs );

Any ideas or recommended approach?

TIA.

You can't do that in the java. long is a primitive type, and does because of that not extend Object . Long , which is a wrapper class for long , does and can be cast to an Object . To create a Long[] from a long[] you will need to go through every value of long[] and copy that to Long[] :

long[] primitiveLong;
Long[] wrappedLong = new Long[primitiveLong.length];
for (int i=0; i<primitiveLong.length; i++) {
    wrappedLong[i] = primitiveLong[i];
}

Then you can cast it to an array of Object :

Object[] objs = wrappedLong;

Or you can even make the wrappedLong of type Object directly so you don't need the casting.

使用Apache Commons的ArrayUtils.toObject这样做的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM