• Java 数据结构教程

合并两个哈希表



HashTable 类的 putAll() 方法接受一个 map 对象作为参数,将所有内容添加到当前哈希表中,并返回结果。

使用此方法,您可以合并两个哈希表的内容。

示例

import java.util.Hashtable;

public class JoiningTwoHashTables {
   public static void main(String args[]) {
      String str;
      Hashtable hashTable1 = new Hashtable();
      hashTable1.put("Ram", 94.6);
      hashTable1.put("Rahim", 92);
      hashTable1.put("Robert", 85);
      hashTable1.put("Roja", 93);
      hashTable1.put("Raja", 75);
      
      System.out.println("Contents of the 1st hash table :"+hashTable1);
      
      Hashtable hashTable2 = new Hashtable();
      hashTable2.put("Sita", 84.6);
      hashTable2.put("Gita", 89);
      hashTable2.put("Ramya", 86);
      hashTable2.put("Soumaya", 96);
      hashTable2.put("Sarmista", 92);      
      System.out.println("Contents of the 2nd hash table :"+hashTable2);
      hashTable1.putAll(hashTable2);      
      System.out.println("Contents after joining the two hash tables: "+hashTable1);
   }
}

输出

Contents of the 1st hash table :{Rahim = 92, Roja = 93, Raja = 75, Ram = 94.6, Robert = 85}
Contents of the 2nd hash table :{Sarmista = 92, Soumaya = 96, Sita = 84.6, Gita = 89, Ramya = 86}
Contents after joining the two hash tables: {Soumaya = 96, Robert = 85, Ram = 94.6, Sarmista = 92, 
   Raja = 75, Sita = 84.6, Roja = 93, Gita = 89, Rahim = 92, Ramya = 86}
广告