2

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.

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

6 Comments

+1 I believe that is the requirement for the copyOf method mentioned.
This is a copy not a cast.
Thanks. Is there a quick way to convert from long to Long ? I am working with an API that provides long[] instead of Long[].
@Gili, how will I do a cast? I surely cannot do (Long[])new long[]{1,2}
@KNji, the correct answer is: "What you are asking for is impossible in Java, however you can make a copy like this..."
|
3

Use Apache Commons' ArrayUtils.toObject which does exactly this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.