gpt4 book ai didi

java - 为什么 HashMap 不接受 HashMap 实例?

转载 作者:行者123 更新时间:2023-11-30 07:59:04 33 4
gpt4 key购买 nike

我是 Java 泛型的新手,面临以下问题。我有这样的方法,

private static void fillDescriptiveData(HashMap<String, Object> output, String attributeMapping) {
for (Map.Entry<String, Object> outputInEntry : output.entrySet()) {
String outputKey = outputInEntry.getKey();
String outputValue = outputInEntry.getValue().toString();
outputValue = getDescriptiveDataForOutput(outputKey, outputValue, attributeMapping);
outputInEntry.setValue(outputValue);
}
}

现在,如果我按以下方式调用 API

HashMap<String, Object> ObjectMap = new HashMap<String, Object>();
HashMap<String, List> listMap = new HashMap<String, List>();
  • fillDescriptiveData(ObjectMap,"here");
    这个工作正常。

  • fillDescriptiveData(listMap,"here");此调用给出错误

The method fillDescriptiveData(HashMap, String) in the type CustomAttribute is not applicable for the arguments (HashMap, String)`

为什么?

为了解决这个问题,我又遇到了一个问题,

private static void fillDescriptiveData(HashMap<String, ? extends Object> output, String attributeMapping) {
for (Map.Entry<String, ? extends Object> outputInEntry : output.entrySet()) {
String outputKey = outputInEntry.getKey();
String outputValue = outputInEntry.getValue().toString();
outputValue = getDescriptiveDataForOutput(outputKey, outputValue, attributeMapping);
outputInEntry.setValue(outputValue); /* Error comes at this line */
}
}

HashMap<String, ? extends Object> ObjectMap = new HashMap<String, Object>();
HashMap<String, List> listMap = new HashMap<String, List>();
fillDescriptiveData(ObjectMap,"here");
fillDescriptiveData(listMap,"here");

行错误 - outputInEntry.setValue(outputValue);

The method setValue(capture#4-of ? extends Object) in the type Map.Entry is not applicable for the arguments (String)

为什么?

避免此问题的最佳方法是什么?

最佳答案

这是可以使用类型变量的情况:

private static <T> void  fillDescriptiveData(Map<String, T> output,String attributeMapping)
{
for(Map.Entry<String, T> outputInEntry : output.entrySet())
{
String outputKey = outputInEntry.getKey();
String outputValue = outputInEntry.getValue().toString();
outputValue = getDescriptiveDataForOutput(outputKey, outputValue, attributeMapping);
outputInEntry.setValue((T) outputValue);
}
}

更具体地说, map 中的第二个类型参数是无界的。 Object不会在这里工作,因为它是特定的类。 ? extends Object有点废话。就HashMap<String, ?>在您只阅读 map 之前会一直有效,但是您将无法在此处放置任何内容。所以只有一种方法——使用类型变量。

编辑:还有一件事:请尽可能使用接口(interface)。所以这里不是HashMap<String, T>更好用Map<String, T> .这不是错误,只是良好和适当的代码风格。

关于java - 为什么 HashMap<String, Object> 不接受 HashMap<String, List> 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39746428/

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