Java 如何将泛型数组列表强制转换为泛型数组

Java 如何将泛型数组列表强制转换为泛型数组,java,arrays,generics,arraylist,casting,Java,Arrays,Generics,Arraylist,Casting,在我的pvsm中调用printary时,我一直收到的错误是: Exception in thread "main" java.lang.ClassCastException: java.base/[Ljava.lang.Object; cannot be cast to java.base/[Ljava.lang.Integer 我知道问题出在R[]result=(R[])list.toArray()上。。我不知道如何将ArrayList转换为数组,同时将其转换为泛型。注意:我无法更

在我的pvsm中调用
printary
时,我一直收到的错误是:

Exception in thread "main" java.lang.ClassCastException: 
    java.base/[Ljava.lang.Object; cannot be cast to java.base/[Ljava.lang.Integer
我知道问题出在
R[]result=(R[])list.toArray()上。
。我不知道如何将ArrayList转换为数组,同时将其转换为泛型。注意:我无法更改函数
map
的参数或添加任何新函数

public class Homework2 {

    public static void main(String[] args){
        Function<Integer,Integer> function = new CalculateSuccessor();
        Double[] d= {2.0,4.0,8.0};
        Integer[] i= {2,4,8};
        printArray(map(function,i));
    }

    @SuppressWarnings("unchecked")
    public static <R,D> R[] map(Function<R,D> function, D[] array){
        ArrayList<R> list = new ArrayList<>();
        for (D element: array){
           list.add(function.apply(element));
        }


        // THIS LINE OF DAMN CODE
        R[] result = (R[]) list.toArray();

        return result;
    }

    public static <R> void printArray(R[] array){
        System.out.print("{ ");
        for (R element: array){
            System.out.print(element + ", ");
        }
        System.out.print("}");
    }

    public static class CalculateSuccessor implements Function<Integer,Integer> {
        @Override
        public Integer apply(Integer parameter) {
            return parameter * 2;
        }
    } //End CalcSuc

} //End Homework2
公共课家庭作业2{
公共静态void main(字符串[]args){
函数函数=新的CalculateSuccessor();
双[]d={2.0,4.0,8.0};
整数[]i={2,4,8};
printArray(映射(函数,i));
}
@抑制警告(“未选中”)
公共静态R[]映射(函数,D[]数组){
ArrayList=新建ArrayList();
for(D元素:数组){
list.add(function.apply(element));
}
//这行该死的代码
R[]结果=(R[])list.toArray();
返回结果;
}
公共静态void printary(R[]数组){
系统输出打印(“{”);
for(R元素:数组){
系统输出打印(元素+“,”);
}
系统输出打印(“}”);
}
公共静态类CalculateSuccessor实现函数{
@凌驾
公共整数应用(整数参数){
返回参数*2;
}
}//结束CalcSuc
}//结束家庭作业2
在另一节课上我有

public interface Function<R,D> {
     public R apply(D parameter);
}
公共接口功能{
公共R应用(D参数);
}

这是函数所需的。应用。我的教授坚持使用这个函数而不是导入函数。

第一部分,您需要
,以便动态创建数组
R[]
。我更喜欢
array.toString
而不是实现我自己的版本。我还需要一个
函数
(不是
函数
)。但是做这些改变就像

public static void main(String[] args) {
    Function<Integer, Integer> function = new CalculateSuccessor();
    Double[] d = { 2.0, 4.0, 8.0 };
    Integer[] i = { 2, 4, 8 };
    System.out.println(Arrays.toString(map(Integer.class, function, i)));
}

public static <R, D> R[] map(Class<R> cls, Function<D, R> function, D[] array) {
    ArrayList<R> list = new ArrayList<>();
    for (D element : array) {
        list.add(function.apply(element));
    }
    return list.toArray((R[]) Array.newInstance(cls, list.size()));
}

您可以从
函数
中提取类型信息,因为它是用实际的类实现的。再加上@Elliott Frisch的回答

public static <R, D> R[] map(Function<D, R> function, D[] array) {
    ArrayList<R> list = new ArrayList<>();
    for (D element : array) {
        list.add(function.apply(element));
    }
    Class<?> componentClass = extractReturnType(function)
    return list.toArray((R[]) Array.newInstance(componentClass, list.size()));
}

private static Class<?> extractReturnType(Function<?, ?> function) {
    Type[] interfaces = function.getClass().getGenericInterfaces();
    for(Type iface:interfaces) {
        if (iface instanceof ParameterizedType && Function.class.equals(((ParameterizedType) iface).getRawType())) {
            return (Class<?>) ((ParameterizedType) iface).getActualTypeArguments()[1];
        }
    }
    throw new IllegalArgumentException("Unable to extract type information");
}
公共静态R[]映射(函数,D[]数组){
ArrayList=新建ArrayList();
for(D元素:数组){
list.add(function.apply(element));
}
类componentClass=extractReturnType(函数)
返回list.toArray((R[])Array.newInstance(componentClass,list.size());
}
私有静态类extractReturnType(函数){
类型[]interfaces=function.getClass().getGenericInterfaces();
用于(iface类型:接口){
if(iface instanceof ParameterizedType&&Function.class.equals(((ParameterizedType)iface.getRawType())的实例){
返回(类)((ParameterizedType)iface.getActualTypeArguments()[1];
}
}
抛出新的IllegalArgumentException(“无法提取类型信息”);
}

list.add(function.apply(element)),在此之前,我在
list.add(function.apply(element))上得到一个错误对不起,我忘了包括我正在使用的界面!不要使用数组。它们真的不能很好地处理泛型。使用收藏。我会的!但作业的目标是理解概念和函数必须应用于数组:(我也尝试过这种方法,但是根据作业和评分方式,我不允许更改函数的参数。感谢您的回答:)我明白了。但这是一个非常有限的解决方案。@tsolakp可以随意提供一个更通用的解决方案。我会在你的问题解决后立即删除这个问题。仅仅因为没有好的解决方案并不意味着你可以提供一个大部分时间都不起作用的解决方案。
public static <R, D> R[] map(Function<D, R> function, D[] array) {
    ArrayList<R> list = new ArrayList<>();
    for (D element : array) {
        list.add(function.apply(element));
    }
    Class<?> componentClass = extractReturnType(function)
    return list.toArray((R[]) Array.newInstance(componentClass, list.size()));
}

private static Class<?> extractReturnType(Function<?, ?> function) {
    Type[] interfaces = function.getClass().getGenericInterfaces();
    for(Type iface:interfaces) {
        if (iface instanceof ParameterizedType && Function.class.equals(((ParameterizedType) iface).getRawType())) {
            return (Class<?>) ((ParameterizedType) iface).getActualTypeArguments()[1];
        }
    }
    throw new IllegalArgumentException("Unable to extract type information");
}