简体   繁体   English

如何将 java Object 转换为 Object[]?

[英]how to cast java Object to Object[]?

How to cast java Object to java Object[] or Integer[] Error(I cannot be cast to [Ljava.lang.Object;);如何将 java Object 转换为 java Object[] 或 Integer[] 错误(我无法转换为 [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)

You are trying to cast primitive types to Object which is not allowed.您正在尝试将原始类型Object为不允许的Object

You need Wrapper classes for this approach.对于这种方法,您需要Wrapper类。 Eg:例如:

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

Ideone demo Ideone 演示

Note: This does not support calculating sum results outside the double range.注意:这不支持计算double精度范围之外的总和结果。 You should look into BigDecimal if you need that.如果需要,您应该查看 BigDecimal。

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[] .您需要使用Integer[]而不是int[]

As others pointed out, you should use Wrapper Types here, for example Integer over the primitive int.正如其他人指出的那样,您应该在这里使用 Wrapper Types,例如在原始 int 上使用 Integer。 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.此处发生 classCastException 是因为它试图将原始 int 类型转换为 Object 类型,并且通过加宽或未检查的收缩都无法从 int 到达 Object,因为 int 不继承自 Object 类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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