简体   繁体   English

将对象数组转换回整数数组时遇到麻烦

[英]Trouble with casting array of objects back to an array of integers

When I go to run this I get the error: 当我运行它时,出现错误:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; 线程“主”中的异常java.lang.ClassCastException:[Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer; 无法转换为[Ljava.lang.Integer; at Main.main(Main.java:30) 在Main.main(Main.java:30)

public class Main 
{ 
    private interface Function<R, D> 
    { 
        public R apply(D parameter);
    }

    public static void main(String[] args) 
    {           
        // Example 1
        Function<Integer, Integer> function = new CalculateSuccessor();
        Integer[] integerArray = {1, 3, 4, 2, 5};
        PrintArray(map(function, integerArray)); // map returns {2, 4, 5, 3, 6}  <--- line 30
    }

    @SuppressWarnings({"unchecked"})
    public static <R, D> R[] map(Function<R, D> function, D[] array)
    {
        R[] results = (R[]) new Object[array.length];

        // Iterate through the source array, apply the given function, and record results
        for (int i = 0; i < array.length; i++)
        {
            results[i] = (R)function.apply(array[i]);
        }

        return results;  
    }

    public static <T> void PrintArray(T[] array)
    {
        for (T element : array)
        {
            System.out.println(element.toString());
        }   
    } 
}

Problem is the result array is created as new Object[array.length]. 问题是结果数组被创建为新的Object [array.length]。 The cast (R[]) doesn't convert this array to a different type, it just tells the compiler to treat it like R[]. 强制转换(R [])不会将此数组转换为其他类型,它只是告诉编译器将其视为R []。 See Quick Java question: Casting an array of Objects into an array of my intended class . 请参见快速Java问题:将Objects数组转换为所需类的数组 Creating an array of generic type is a bit nasty - you can google for various solutions, eg How to create a generic array in Java? 创建通用类型的数组有点麻烦-您可以在Google上搜索各种解决方案,例如, 如何在Java中创建通用数组? - but generally the simplest approach is to use a list instead of an array: you can create it with new ArrayList<R> -但最简单的方法通常是使用列表而不是数组:您可以使用新的ArrayList <R>创建它

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

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