Как исправить ошибку arrayindexoutofboundsexception в моей программе
Functional programming languages have a concept called map that takes a function and an array as parameters, and it returns the array produced by applying the function to every element of the original array. Given that our recent introduction to the edu.psu.cmpsc221.Function interface used static members, our map function will also be static and will have the following signature: public static <R, D> R[] map(Function<R, D> function, D[] array) The syntax for this generic function is slightly different from the syntax of the other Java generics that we have seen in class (there is an additional pair of type variables that follows the static keyword). This is the syntax Java uses for a static generic method. To help clarify whatmapis doing, a few example uses are provided: // 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} // Example 2 Function<Integer, String> anotherFunction = new CalculateLength(); String[] stringArray = { "Java", "C++", "Smalltalk" }; PrintArray(map(anotherFunction, stringArray)); // map returns {4, 3, 9} // Example 3 Function<Double, Double> tripleFunction = new CalculateTriple(); Double[] doubleArray = { 2.0, 4.0, 5.0, 1.0 }; PrintArray(map(tripleFunction, doubleArray)); // map returns {6.0, 12.0, 15.0, 3.0} Please note that while the solution is actually quite short, this is a challenging problem because Java willlikely get in your way and prevent you from implementing “obvious” solutions (recall that Java generics areknown to not play nicely with arrays).
Что я уже пробовал:
public static void main(String[] args) { Function<Integer, Integer> function0 = new CalculateSuccessor(); Integer[] integerArray = {1,3,4,2,5}; //creating a Integer array PrintArray(map(function0, integerArray)); Function<Integer, String> function1 = new CalculateLength(); String[] stringArray = {"Java", "C++", "Smalltalk"}; PrintArray(map(function1, stringArray)); Function<Double, Double> function2 = new CalculateTriple(); // Double[] doubleArray = {2.0,4.0,5.0,1.0}; Double[] doubleArray = { }; // ERROR HERE THIS NEED TO BE FIX PrintArray(map(function2, doubleArray)); } @SuppressWarnings("unchecked") public static <R, D> R[] map(Function<R, D> function, D[] array ) { R[] returnArray = (R[])Array.newInstance(function.apply(array[0]).getClass(), array.length); // ERROR HERE THIS NEED TO BE FIX for(int i = 0;i < array.length; i++) { returnArray[i] = function.apply(array[i]); } return returnArray; }