gpt4 book ai didi

Java 泛型 : Calling generic Method "...is not applicable for the arguments..."

转载 作者:行者123 更新时间:2023-12-01 23:29:31 24 4
gpt4 key购买 nike

我有 2 个 HashMap,其中 <Integer, "sometype"> 。所以“某种类型”可能有所不同,因此我试图使其通用。在这种情况下,我的两个变量如下

private HashMap<Integer, UI_FieldPV> values_map = new HashMap<Integer, UI_FieldPV>();
private HashMap<Integer, JComponent> input_map = new HashMap<Integer, JComponent>();

该方法的第一次调用没问题:

this.input_map = MapOperations.<JComponent> rearrengeHashMapIdx(this.input_map);

第二个调用传递一个带有 <Integer, CustomClass> 的 HashMap

this.values_map = MapOperations.<UI_FieldPV>rearrengeHashMapIdx(this.input_map);

这给了我以下错误:

The parameterized method <UI_FieldPV>rearrengeHashMapIdx(HashMap<Integer,UI_FieldPV>) of type UI.MapOperations is not applicable for the arguments (HashMap<Integer,JComponent>)

包含泛型方法的类的编码(顺便说一句:我尝试在调用类中创建泛型方法,但它不起作用。我是否必须创建一个嵌入类才能使泛型方法参数起作用?)

private static class MapOperations<T> {
public static <T> HashMap<Integer, T> rearrengeHashMapIdx(HashMap<Integer, T> source) {

HashMap<Integer, T> temp = new HashMap<Integer, T>();
for (Integer i = 0; i < 81; i++) {
Integer rowNum = (i / 3) % 3;
Integer block = i / 9;
Integer delta = (rowNum - block);
Integer newIdx = i + (delta * 6);
temp.put(i, source.get(newIdx));
}
return temp;
}
}

那我做错了什么?提前感谢您的帮助!

最佳答案

编译器错误已经很清楚了。第一次调用方法:

this.input_map = MapOperations.<JComponent>rearrengeHashMapIdx(this.input_map);

将返回 HashMap<Integer, JComponent> ,因为您已经给出了显式类型参数(好吧,这里实际上并不需要。类型 T 无论如何都会从您传递的 HashMap 的类型中推断出来)。没关系,因为您已经声明了您的 input_map仅属于该类型。

那么你正在传递input_map作为下一个方法调用的参数:

this.values_map = MapOperations.<UI_FieldPV>rearrengeHashMapIdx(this.input_map);

现在,根据该方法的声明,该方法的参数应为 HashMap<Integer, T> 类型。在第二个方法调用中,类型参数T推断为UI_FieldPV 。因此,该方法需要 HashMap<Integer, UI_FieldPV> ,但您正在传递 HashMap<Integer, JComponent> 。当然,方法调用会失败,因为两个映射不兼容。

也许,在第二次调用中,您打算传递 values_map作为论证。所以这会很好地工作:

this.values_map = MapOperations.<UI_FieldPV>rearrengeHashMapIdx(this.values_map);

请注意类型参数 T方法中使用的类型与参数T无关。与类声明一起使用,尽管这在这里没有任何区别。但仅供引用。

关于Java 泛型 : Calling generic Method "...is not applicable for the arguments...",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19548233/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com