Java面试题 P12:HashMap和HashTable的区别?底层是怎么实现的?
区别:
1、HashMap:是线程不安全的,HashTable:每个方法都加了个线程锁(synchronized 修饰),是线程安全的
2、HashMap允许key和value为null,而HashTable不允许
底层实现:数据+链表实现
代码示例:
1 public static void main(String[] args) 2 { 3 //HashMap 4 HashMap<String,String> map=new HashMap<>(); 5 map.put("apple","red"); 6 map.put("banana","yellow"); 7 map.put("orange","orange"); 8 9 String value=map.get("apple"); 10 System.out.println(value);//输出 red 11 12 map.remove("banana"); 13 System.out.println(map); //输出 {orange=orange, apple=red} 14 15 map.put(null,"nullvalue"); 16 System.out.println(map); //输出 {orange=orange, null=nullvalue, apple=red} 17 18 map.put("nullkey",null); 19 System.out.println(map); //输出 {orange=orange, null=nullvalue, apple=red, nullkey=null} 20 21 //HashTable 独特的用法 22 Hashtable<String,String> table=new Hashtable<>(); 23 table.put("apple","red"); 24 table.put("banana","yellow"); 25 table.put("orange","orange"); 26 27 String value1=table.get("apple"); 28 System.out.println(value1); 29 30 table.remove("banana"); 31 32 33 }