I have created a hashtable in java as: Hashtable<Integer, String> h = new Hashtable<Integer, String>();
Now I have populated some values in this Hashtable as:
1 -> "A"
2 -> "B"
3 -> "C"
4 -> "D"
Now I want to check if a particular key is present in the hashtable. If it is indeed present then I will modify the value part of the HashTable for that particular key. For e.g. I want to check if the key = 2 is present or not. Since it is present I want to modify the value part with 'F'.
So now the entry will look like: 2 -> "B F".
So the Hashtable will become as:
1 -> "A"
2 -> "B F"
3 -> "C"
4 -> "D"
Can someone please suggest me the code to this problem in java.
Many thanks in advance.
Well, dont confuse too much here. As you are new first get a solution here.
Hash_table.containsKey(key_element);
You can put that in if condition and do your stuff. Here is full code
// Java code to illustrate the containsKey() method
import java.util.*;
public class Hash_Table_Demo {
public static void main(String[] args)
{
// Creating an empty Hashtable
Hashtable<Integer, String> hash_table =
new Hashtable<Integer, String>();
// Putting values into the table
hash_table.put(1, "A");
hash_table.put(2, "B");
hash_table.put(3, "C");
hash_table.put(4, "D");
// Displaying the Hashtable
System.out.println("Initial Table is: " + hash_table);
// Checking for the key_element '2'
if(hash_table.containsKey(2))){ //true
hash_table.replace(2, "BF"); // Your Soultion Here
};
System.out.println("New Table is: " + hash_table);
}
}