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
- 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);
- }
- }
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
- 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);
- }
- }
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