相关疑难解决方法(0)

使用通配符和通配符的问题

我有一个方法,返回map定义为:

public Map<String, ?> getData();
Run Code Online (Sandbox Code Playgroud)

这个方法的实际实现对我来说并不清楚,但是,当我尝试这样做时:

obj.getData().put("key","value")
Run Code Online (Sandbox Code Playgroud)

我得到以下编译时错误消息:

方法put(String,capture#9-of?)在Map类型中不适用于参数(String,String)

问题是什么?是String不是输入任何内容?

提前致谢.

java generics arguments wildcard map

11
推荐指数
3
解决办法
1万
查看次数

Java Map编译器错误与泛型

// I know that this method will generated duplicate 
// trim keys for the same value but I am just
// trying to understand why we have a compile error:
// The method put(String, capture#11-of ?) in the type
// Map<String,capture#11-of ?> is not applicable for the arguments
// (String, capture#12-of ?)

void trimKeyMap(Map<String, ?> map){
  for (String key : map.keySet()) {
    map.put(StringUtils.trim(key), map.get(key)); // compile error
  }
}
Run Code Online (Sandbox Code Playgroud)

为什么我们想要的价值 map.get(key)来自不同的类型?

java generics map

3
推荐指数
1
解决办法
1236
查看次数

我的方法通用参数有什么问题

我想用通用映射填充List,但我的代码不能编译.我已经为这个问题准备了最简单的例子.在上面的注释问题中,我把错误放在下面的行中.

void populateList(List<? extends Map<String,?>> list) {
    list.clear();
    HashMap<String, ?>  map;
    map = new HashMap<String,String>();
    //The method put(String, capture#2-of ?) in the type HashMap<String,capture#2-of ?> is not applicable for the arguments (String, String)
    map.put("key", "value"); // this line does not compile
    // The method add(capture#3-of ? extends Map<String,?>) in the type List<capture#3-of ? extends Map<String,?>> is not applicable for the arguments (HashMap<String,capture#5-of ?>)
    list.add(map);      //This line does not compile
}
Run Code Online (Sandbox Code Playgroud)

为什么会这样?有什么我不明白的吗?

编辑1

根据下面的一个答案,他指出了?代表未知类型而不是Object的后代.这是一个有效的观点.而且,在方法内部我知道进入map的类型,所以我相应地修改了我的简单代码.

void populateList(List<? extends Map<String,?>> list) {
    list.clear(); …
Run Code Online (Sandbox Code Playgroud)

java android

3
推荐指数
1
解决办法
1954
查看次数

将Java Generics与HashMap一起使用

我有一个B和C类,它们都扩展到A类:

public class B extends A {...}
public class C extends A {...}
Run Code Online (Sandbox Code Playgroud)

如何以这种方式将Java泛型与HashMap一起使用?

B b = new B();
C c = new C();

Map<String, ? extends A> map = new HashMap<String, A>();

map.put("B", b);
map.put("C", c);
Run Code Online (Sandbox Code Playgroud)

Eclipse始终显示错误:

方法put(String,capture#1-of?extends A)在Map类型中不适用于参数(String,B)

方法put(String,capture#1-of?extends A)在Map类型中不适用于参数(String,C)

java generics

0
推荐指数
1
解决办法
2万
查看次数

标签 统计

java ×4

generics ×3

map ×2

android ×1

arguments ×1

wildcard ×1