Add elements in HashTable

We can use put() and putAll() methods of HashTable to add elements to HashTable

Object put(Object key, Object value);


Associates the specified value with the specified key in this map.

This method is used to add single key-value pair to the HashTable

Example

  1. import java.util.*;
  2. public class HashTablePutExample {
  3. public static void main(String args[]) {
  4.  Hashtable<Integer,String> hashTable =new Hashtable<Integer,String>();
  5.  
  6.       hashTable.put(1, "One");
  7.       hashTable.put(2, "Two");
  8.       hashTable.put(3, "Three");
  9.      
  10.  
  11. System.out.println(hashTable);
  12.  
  13. }
  14. }
import java.util.*;
public class HashTablePutExample {
public static void main(String args[]) {
 Hashtable<Integer,String> hashTable =new Hashtable<Integer,String>(); 

      hashTable.put(1, "One");
      hashTable.put(2, "Two");
      hashTable.put(3, "Three");
      

System.out.println(hashTable);

}
}


void putAll(Map m);


Copies all of the mappings from the specified map to this hash table.

This method is used to add all key-value pairs from another Map to this HashTable

Example

  1. import java.util.*;
  2. public class HashTablePutAllExample {
  3. public static void main(String args[]) {
  4.  
  5.  Hashtable<Integer,String> hashTable=new Hashtable<Integer,String>();
  6.  
  7.       hashTable.put(1, "One");
  8.       hashTable.put(2, "Two");
  9.       hashTable.put(3, "Three");
  10.      
  11. Hashtable<Integer,String> hashTable1=new Hashtable<Integer,String>();
  12. hashTable1.put(4, "Four");
  13.       hashTable1.put(5, "Five");
  14.  
  15. hashTable.putAll(hashTable1);
  16. System.out.println(hashTable);
  17.  
  18. }
  19. }
import java.util.*;
public class HashTablePutAllExample {
public static void main(String args[]) {

 Hashtable<Integer,String> hashTable=new Hashtable<Integer,String>();

      hashTable.put(1, "One");
      hashTable.put(2, "Two");
      hashTable.put(3, "Three");
      
Hashtable<Integer,String> hashTable1=new Hashtable<Integer,String>();
hashTable1.put(4, "Four");
      hashTable1.put(5, "Five");

hashTable.putAll(hashTable1);
System.out.println(hashTable);

}
}
Note : We can see that hashTable1 has 2 key-value pairs and these 2 are added to main HashTable using putAll() 
             method

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on