0% found this document useful (0 votes)
9 views5 pages

Gmail - HashTable

Hashtable is a synchronized collection class in Java that stores key/value pairs but is considered outdated compared to HashMap. It does not allow null keys or values and provides methods for insertion, retrieval, updating, deletion, and iteration. While it ensures thread safety, its performance overhead makes HashMap a preferred choice in modern applications unless synchronization is necessary.

Uploaded by

Nagasai Maddula
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views5 pages

Gmail - HashTable

Hashtable is a synchronized collection class in Java that stores key/value pairs but is considered outdated compared to HashMap. It does not allow null keys or values and provides methods for insertion, retrieval, updating, deletion, and iteration. While it ensures thread safety, its performance overhead makes HashMap a preferred choice in modern applications unless synchronization is necessary.

Uploaded by

Nagasai Maddula
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

HashTable

1 message

Nagasai Maddula <[email protected]> Sun, 19 Jan, 2025 at 15:15


To: Nagasai Maddula <[email protected]>

Hashtable in Java: How It Works and Its Methods

Hashtable is a part of the Java Collections Framework but is considered somewhat outdated compared to more modern
collections like HashMap. It is a collection of key/value pairs where both keys and values are objects.

How it Works:

Internal Structure: Hashtable internally uses a hash table (array of linked lists). The keys are hashed, and the hash codes determine
the bucket in which the key-value pair will be placed.

Synchronization: Unlike HashMap, Hashtable is synchronized, making it thread-safe. This means that only one thread can access a
Hashtable at a time, which can lead to performance issues in multi-threaded environments if synchronization is not needed.

Null Keys/Values: Hashtable does not allow null keys or null values. In contrast, HashMap allows one null key and multiple null
values.

---

Common Methods of Hashtable

1. put(K key, V value)

Description: Inserts a key-value pair into the Hashtable.

Return Type: V (previous value associated with the key, or null if no mapping existed).

Example:

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


table.put("Apple", 50); // Inserts a key-value pair
System.out.println(table); // Output: {Apple=50}

2. get(Object key)

Description: Retrieves the value associated with the given key.

Return Type: V (the value associated with the key, or null if not found).

Example:

Integer value = table.get("Apple");


System.out.println(value); // Output: 50

3. remove(Object key)

Description: Removes the key-value pair from the Hashtable based on the given key.

Return Type: V (the value that was associated with the key, or null if no mapping existed).

Example:

table.remove("Apple"); // Removes the "Apple" key-value pair


System.out.println(table); // Output: {}
4. containsKey(Object key)

Description: Checks if the Hashtable contains the specified key.

Return Type: boolean (true if the key exists, false otherwise).

Example:

boolean exists = table.containsKey("Apple");


System.out.println(exists); // Output: false

5. containsValue(Object value)

Description: Checks if the Hashtable contains the specified value.

Return Type: boolean (true if the value exists, false otherwise).

Example:

boolean contains = table.containsValue(50);


System.out.println(contains); // Output: false

6. size()

Description: Returns the number of key-value pairs in the Hashtable.

Return Type: int (size of the Hashtable).

Example:

System.out.println(table.size()); // Output: 0

7. clear()

Description: Removes all key-value pairs from the Hashtable.

Return Type: void

Example:

table.clear(); // Clears all elements from the table


System.out.println(table); // Output: {}

8. keys()

Description: Returns an enumeration of the keys in the Hashtable.

Return Type: Enumeration<K>

Example:

Enumeration<String> keys = table.keys();


while (keys.hasMoreElements()) {
System.out.println(keys.nextElement());
}

9. values()

Description: Returns a collection of all values in the Hashtable.

Return Type: Collection<V>

Example:
Collection<Integer> values = table.values();
for (Integer val : values) {
System.out.println(val);
}

10. putAll(Map<? extends K, ? extends V> m)

Description: Copies all key-value pairs from another map (or Hashtable) into the current Hashtable.

Return Type: void

Example:

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


newTable.put("Banana", 20);
table.putAll(newTable); // Adds all entries from newTable to table
System.out.println(table); // Output: {Banana=20}

---

Create, Update, Retrieve, Delete, Sort

1. Create a Hashtable:

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


table.put("Apple", 50);
table.put("Banana", 20);
table.put("Mango", 30);
System.out.println(table); // Output: {Apple=50, Banana=20, Mango=30}

2. Update a Value:

To update the value associated with an existing key, you simply use the put() method, which replaces the old value for that key.

table.put("Apple", 60); // Update value of "Apple"


System.out.println(table); // Output: {Apple=60, Banana=20, Mango=30}

3. Retrieve a Value:

To retrieve the value associated with a specific key, use the get() method.

Integer value = table.get("Banana");


System.out.println(value); // Output: 20

4. Delete a Key-Value Pair:

To delete a specific key-value pair, use the remove() method.

table.remove("Mango"); // Removes the key "Mango" and its value


System.out.println(table); // Output: {Apple=60, Banana=20}

5. Sort the Hashtable:

Important Note: Hashtable does not support direct sorting as it is based on hashing. If you need to sort the keys or values, you can
convert the Hashtable to a List or a TreeMap (which is inherently sorted).

Sorting by Keys:

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


table.put("Banana", 20);
table.put("Apple", 50);
table.put("Mango", 30);

// Converting Hashtable to TreeMap to sort by keys


TreeMap<String, Integer> sortedTable = new TreeMap<>(table);
System.out.println(sortedTable); // Output: {Apple=50, Banana=20, Mango=30}
Sorting by Values:

To sort by values, convert the Hashtable to a List of Map.Entry objects, then sort it:

List<Map.Entry<String, Integer>> list = new ArrayList<>(table.entrySet());


list.sort(Map.Entry.comparingByValue());
System.out.println(list); // Output: [(Banana=20), (Mango=30), (Apple=50)]

---

Program Example

import java.util.*;

public class HashtableExample {


public static void main(String[] args) {
// Creating a Hashtable
Hashtable<String, Integer> table = new Hashtable<>();
table.put("Apple", 50);
table.put("Banana", 20);
table.put("Mango", 30);

// Retrieve value
System.out.println("Value of Banana: " + table.get("Banana"));

// Update value
table.put("Apple", 60);
System.out.println("Updated table: " + table);

// Remove an entry
table.remove("Mango");
System.out.println("After removal of Mango: " + table);

// Sorting the Hashtable by keys


TreeMap<String, Integer> sortedTable = new TreeMap<>(table);
System.out.println("Sorted by keys: " + sortedTable);

// Sorting by values
List<Map.Entry<String, Integer>> list = new ArrayList<>(table.entrySet());
list.sort(Map.Entry.comparingByValue());
System.out.println("Sorted by values: " + list);
}
}

Output:

Value of Banana: 20
Updated table: {Apple=60, Banana=20, Mango=30}
After removal of Mango: {Apple=60, Banana=20}
Sorted by keys: {Apple=60, Banana=20}
Sorted by values: [(Banana=20), (Apple=60)]

---

Summary:

Hashtable is a legacy collection class that is synchronized and thread-safe but has performance overhead due to synchronization.

It does not allow null keys or values.

The methods provided allow for insertion, retrieval, updating, deletion, and basic iteration over key-value pairs.

It is generally recommended to use HashMap instead of Hashtable in modern applications, unless synchronization is specifically
required.

You might also like