2

How to cast java Object to java Object[] or Integer[] Error(I cannot be cast to [Ljava.lang.Object;);

public class LongestAscendingSumSequence {

    public static void main(String[] ar) {
        int[] arr = { 1, 2, 3, 20, 3, 25, 30, 31, 32, 33, 34 };
        System.out.println(getSum(arr));
        float[] brr = { 1.3f, 2.3f };
        System.out.println(getSum(brr));
        int[] crr = { 1, 2, 3, 20, 3, 25, 30, 31, 32, 33, 34, -2 };
        System.out.println(getSum(crr));

    }

    public static String getSum(Object obj) {
        Object[] objects = (Object[]) obj;

        System.out.println(objects.length);

        return null;
    }
}

Getting error for this

Exception in thread "main" java.lang.ClassCastException: [I cannot be cast to [Ljava.lang.Object;
    at jan25.LongestAscendingSumSequence.getSum(LongestAscendingSumSequence.java:16)
    at jan25.LongestAscendingSumSequence.main(LongestAscendingSumSequence.java:7)
2
  • 2
    ìnt[] is not an Object[], thus the exception. Even covariance does not help in this case. If you were using Integer[] instead of int[], it would be working. Commented Jan 25, 2020 at 8:21
  • This is why the various library functions like Arrays.sort have a bunch of overloads for primitive arrays. Commented Jan 25, 2020 at 9:01

3 Answers 3

3

You are trying to cast primitive types to Object which is not allowed.

You need Wrapper classes for this approach. E.g.:

Integer[] arr = { 1, 2, 3, 20, 3, 25, 30, 31, 32, 33, 34 };
System.out.println(getSum(arr));

Ideone demo

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

Comments

0

As others pointed out, you should use Wrapper Types here, for example Integer over the primitive int. The classCastException here occurs because it is trying to cast a primitive int to Object type and neither by widening or unchecked narrowing can one reach from int to Object as int doesn't inherit from Object type.

Comments

0

Note: This does not support calculating sum results outside the double range. You should look into BigDecimal if you need that.

public static <T extends Number>double getSum(T[] tArray) {
    double sum = 0;
    for (T t : tArray) sum = sum + t.doubleValue();
    return sum;
}

You need to use Integer[] instead of int[].

2 Comments

For whatever reason, I can't edit this. I forgot to note you need to use Integer[] instead of int[]
You do not actually answer the question as of why the ClassCastException occurs.

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.