HashTable是Map另一个实现类,此类实现了一个哈希表,该哈希表将键映射到相应的值。任何非null对象都可以用作键或值。即不允许存储null对象(其他集合是允许的)。
JDK1.0版本就存在的,是最早期的双列集合。线程安全,是同步的(单线程,速度慢)。
HashTable:底层是一个哈希表,是一个线程安全的集合,是单线程集合,速度慢。
HashMap:底层是一个哈希表,是一个线程不安全的集合,是多线程的集合,速度快。
HashMap集合(以及之前学的所有集合):可以存储null值/键。
HashTable集合和Vector集合一样,在JDK1.2版本之后,被更先进的集合取代了。即HashMap和ArrayList,因为多线程速度快。
注意:HashTable的子类Properities依然活跃被使用。
Properities集合是一个唯一和IO流相结合的集合。
举例两者的不同:
public static void main(String[] args) { HashMap<String,String> hashMap = new HashMap<>(); // HashMap允许空值空键 hashMap.put(null,"a"); hashMap.put("b",null); hashMap.put(null,null); // 注意,键重复,值取代 System.out.println(hashMap); // {null=null, b=null} Hashtable<String,String> hashtable = new Hashtable<>(); // 不允许存储空值空键,报错NullPointerException // hashtable.put(null,"a"); System.out.println(hashtable); }
例题:计算一个字符串中字符出现的次数
代码:
public static void main(String[] args) { Scanner sc = new Scanner(System.in); // 键入字符串 System.out.println("请输入一串字符:"); String str = sc.next(); // 转为字符数组 char[] charList = str.toCharArray(); // 创建HashMap集合 HashMap<Character,Integer> hashMap = new HashMap<>(); // 遍历 for (char c:charList) { if(hashMap.get(c) != null){ // 已存在 hashMap.put(c,hashMap.get(c) + 1); } else{ // 第一次存入 hashMap.put(c,1); } } // 遍历HashMap,两种方法,一:将key转为set,再遍历set //二,取出Entry对象,遍历entry对象 // 此处两种都实现,加深代码印象 Set<Character> keySet = hashMap.keySet(); for (char c:keySet) { // 自动拆箱 System.out.println("字符" + c + "出现次数为:" + hashMap.get(c)); } System.out.println("--------------"); // 两种HashMap不同遍历方法,读者可自选其一即可 Set<Map.Entry<Character,Integer>> entryMap = hashMap.entrySet(); Iterator<Map.Entry<Character,Integer>> iterator = entryMap.iterator(); while (iterator.hasNext()){ Map.Entry<Character,Integer> entry = iterator.next(); System.out.println("字符" + entry.getKey() + "出现次数为:" + entry.getValue()); } }
运行截图: