示例未遵循:HashMap 只允许一个键和多个空值
Example not following: HashMap allows only one key and multiple null values
今天看了一本书:-
"HashMap allows one null key and multiple null values in a collection."
HashMap<Object,Object> ih=new HashMap<Object,Object>();
Object o1=null;
Integer o2=null;
ih.put(o1,null);
ih.put(new Integer(2),null);
ih.put(o2,new Integer(3));
此示例将两个空对象引用放入映射中。
但是下面的例子编译成功并且运行...
我不明白为什么?
这本书大概的意思是这样的:
- 在一个
HashMap<X, Y>
的可能键中,可以有一个空键;
- 无论键是什么(甚至是 null!),与此键关联的值都可以是 null。
因此,您的代码正常工作是完全正常的。只是这里的书的文字比较混乱
当然,这完全取决于 Map
的实现;其中一些,例如 ConcurrentHashMap
,将不允许空键或空值。
"HashMap allows one null key and multiple null values in a
collection."
允许一个null
键意味着如果你继续添加null
键,它将覆盖以前的值。实际上,HashMap
中的任何键都是如此。
底线是 - HashMap allows only one key
例如如果您打印 Hashmap
的大小,它将是 2。
System.out.println("size:: "+ih.size());
今天看了一本书:-
"HashMap allows one null key and multiple null values in a collection."
HashMap<Object,Object> ih=new HashMap<Object,Object>();
Object o1=null;
Integer o2=null;
ih.put(o1,null);
ih.put(new Integer(2),null);
ih.put(o2,new Integer(3));
此示例将两个空对象引用放入映射中。
但是下面的例子编译成功并且运行...
我不明白为什么?
这本书大概的意思是这样的:
- 在一个
HashMap<X, Y>
的可能键中,可以有一个空键; - 无论键是什么(甚至是 null!),与此键关联的值都可以是 null。
因此,您的代码正常工作是完全正常的。只是这里的书的文字比较混乱
当然,这完全取决于 Map
的实现;其中一些,例如 ConcurrentHashMap
,将不允许空键或空值。
"HashMap allows one null key and multiple null values in a collection."
允许一个null
键意味着如果你继续添加null
键,它将覆盖以前的值。实际上,HashMap
中的任何键都是如此。
底线是 - HashMap allows only one key
例如如果您打印 Hashmap
的大小,它将是 2。
System.out.println("size:: "+ih.size());