这似乎是一个愚蠢的问题,但我现在正在被它绊倒。为什么会编译?
import java.util.*;
public class Test {
public static void main (String[] argv) throws Exception {
Map<String,String> map = new HashMap<String,String>();
map.get(new ArrayList<String>());
}
}
使用与“String”不兼容的内容调用 get 不应该是非法的吗?
最佳答案
来自 Map 的 Javadocs :
V get(Object key)
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
get 只是一个接受任何对象的方法,并且将(如果存在)返回映射到它的对象。因此,向其传递非字符串是合法的,但是,由于所有键都必须是字符串,因此如果传递非字符串,您将始终得到 null。
关于java - 为什么这段带有泛型的代码可以编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1145121/