简体   繁体   中英

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; cannot be cast to [Ljava.lang.Integer; at 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]. The cast (R[]) doesn't convert this array to a different type, it just tells the compiler to treat it like R[]. See Quick Java question: Casting an array of Objects into an array of my intended class . 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? - but generally the simplest approach is to use a list instead of an array: you can create it with new ArrayList<R>

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