|
|
Program: Basic Hashtable Operations.
Description: |
Below example shows basic operations on Hashtable like creating hashtable object, adding key-value
pair, getting the value based on key, checking hashtable is empty or not, removing an element, and size of the hashtable.
|
Code: |
package com.java2novice.hashtable;
import java.util.Hashtable;
public class MyHashtableOperations {
public static void main(String a[]){
//Create hashtable instance
Hashtable<String,String> ht = new Hashtable<String,String>();
//add key-value pair to hashtable
ht.put("first", "FIRST INSERTED");
ht.put("second", "SECOND INSERTED");
ht.put("third","THIRD INSERTED");
System.out.println(ht);
//getting value for the given key from hashtable
System.out.println("Value of key 'second': "+ht.get("second"));
System.out.println("Is Hashtable empty? "+ht.isEmpty());
ht.remove("third");
System.out.println(ht);
System.out.println("Size of the Hashtable: "+ht.size());
}
}
|
|
Output: |
{third=THIRD INSERTED, second=SECOND INSERTED, first=FIRST INSERTED}
Value of key 'second': SECOND INSERTED
Is Hashtable empty? false
{second=SECOND INSERTED, first=FIRST INSERTED}
Size of the Hashtable: 2
|
|
|
|
|
List Of All Hashtable Sample Programs:- Basic Hashtable Operations.
- How to iterate through Hashtable?
- How to copy Map content to another Hashtable?
- How to search a key in Hashtable?
- How to search a value in Hashtable?
- How to get all keys from Hashtable?
- How to get entry set from Hashtable?
- How to delete all elements from Hashtable?
- How to read elements using Enumeration in Hashtable?
- Hashtable implementation with equals and hashcode example.
- How to fetch values with user define object as keys in Hashtable?
- How to eliminate duplicate keys (user defined objects) with Hashtable?
|
|
|
What is race condition?
A race condition is a situation in which two or more threads or
processes are reading or writing some shared data, and the final
result depends on the timing of how the threads are scheduled.
Race conditions can lead to unpredictable results and subtle
program bugs. A thread can prevent this from happening by locking
an object. When an object is locked by one thread and another
thread tries to call a synchronized method on the same object,
the second thread will block until the object is unlocked.
It is easier to fight for one’s principles than to live up to them.
-- Alfred Adler
|