HashMap 对象的 key、value 值均可为 null。
HahTable 对象的key、value 值均不可为 null。
且两者的的 key 值均不能重复,若添加 key 相同的键值对,后面的 value 会自动覆盖前面的 value,但不会报错。测试代码如下
- public class Test{
- public static void main(String[] args){
- Map<String, String>map = newHashMap<String, String>();//HashMap对象
- Map<String, String>tableMap = newHashtable<String, String>();//HashTable对象
- map.put(null,null);
- System.out.println("hashMap的[key]和[value]均可以为 null:" + map.get(null)); 9.
- try{
- tableMap.put(null,"3");
- System.out.println(tableMap.get(null));
- } catch (Exception e){
- System.out.println("【ERROR】:hashTable的[key]不能为 null");.
- }
- try{
- tableMap.put("3",null);
- System.out.println(tableMap.get("3"));
- } catch (Exception e){
- System.out.println("【ERROR】:hashTable的[value]不能为 null");
-
} -
} -
} -
|
运行结果:
hashMap 的[key]和[value]均可以为 null:null
【ERROR】:hashTable 的[key]不能为 null
【ERROR】:hashTable 的[value]不能为 null