Java Map编译器错误与泛型 [英] Java Map compiler error with generic

查看:151
本文介绍了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
  }
}

我们想要的价值如何将 map.get(key)可以来自不同的类型?

How come the value that we want to put map.get(key) can be from a different type?

推荐答案

问题是编译器只知道密钥类型是未知,但是不知道它是与地图的密钥类型相同的类型类型,从 get()(尽管人类意识到这是一样的)。

The problem is that the compiler only knows the key type is "unknown", but doesn't know it's the same unknown type for the type of the Map's key and the type returned from get() (even though we as humans realize that it's the same).

如果你想让它工作,您必须通过键入方法告知编译器是相同的未知类型,例如:

If you want to make it work, you must tell the compiler it's the same unknown type by typing your method, for example:

void <V> trimKeyMap(Map<String, V> map) {
    for (String key : map.keySet()) {
        map.put(StringUtils.trim(key), map.get(key));
    }
}

这篇关于Java Map编译器错误与泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆