您的位置:首页 > 其它

关于TreeMap、HashMap、HashTable的键是否能为\"\"和Null的问题

2017-04-17 11:33 411 查看
TreeMap键不能为null,HashMap键可以为null。实例代码:  Map<Object,String> treeMap_1 = new TreeMap<Object,String>();
  treeMap_1.put(null, "treeMap_1成功了!");
  Map<String,Object> hashMap_1 = new HashMap<String,Object>();
  hashMap_1.put(null, new String("hashMap_1,ok......"));    
  System.out.println(treeMap_1.get(null));//运行时产生java.lang.NullPointerException异常  System.out.println(hashMap_1.get(null));//打印hashMap_1,ok......   或者:   Map<Object,String> treeMap_2 = new TreeMap<Object,String>();
  treeMap_2.put(null, "treeMap_2成功了!");
  Map<Object,String> hashMap_2 = new HashMap<Object,String>();
  hashMap_2.put(null, "hashMap_2,ok......");
  System.out.println(treeMap_2.get(null));//运行时产生java.lang.NullPointerException异常
  System.out.println(hashMap_2.get(null));//打印hashMap_2,ok...... TreeMap键可以为"",HashMap键可以为""。实例代码:  Map<Object,String> treeMap_1 = new TreeMap<Object,String>();
  treeMap_1.put(new String(""), "treeMap_1成功了!");
  Map<String,Object> hashMap_1 = new HashMap<String,Object>();
  hashMap_1.put("", new String("hashMap_1,ok......"));     
  System.out.println(treeMap_1.get(""));//打印treeMap_1,ok......  System.out.println(hashMap_1.get(""));//打印hashMap_1,ok......   或者:   Map<Object,String> treeMap_2 = new TreeMap<Object,String>();
  treeMap_2.put(new String(""), "treeMap_2成功了!");
  Map<Object,String> hashMap_2 = new HashMap<Object,String>();
  hashMap_2.put(new String(""), "hashMap_2,ok......");
  System.out.println(treeMap_2.get(""));//打印treeMap_2,ok......  System.out.println(hashMap_2.get(""));//打印hashMap_2,ok......   HashTable与TreeMap相同,键不能为null,可以为""。  Map<Object,Object> table_1 = new Hashtable<Object,Object>();
  table_1.put(new String(""), new String("table_1"));
  System.out.println(table_1.get(""));//打印table_1
    
  Map<String,Object> table_2 = new Hashtable<String,Object>();
  table_2.put("", new String("table_2"));
  System.out.println(table_2.get(""));//打印table_2   -------------------------------------------------------------  Map<Object,Object> table_1 = new Hashtable<Object,Object>();
  table_1.put(null, new String("table_1"));  System.out.println(table_1.get(null));//运行时产生java.lang.NullPointerException异常

  Map<String,Object> table_2 = new Hashtable<String,Object>();
  table_2.put(null, new String("table_2"));
  System.out.println(table_2.get(null));//运行时产生java.lang.NullPointerException异常 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: