Java Collection: Hashtable - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Java Collection: Hashtable

Share This

It is used to map keys to values. Please note that the spelling, while you are writing it.

Few important facts of Hashtable are as follows:

  1. It is synchronized.
  2. It stores <key, value> pairs in Hash Table (discussed in Data Structure).
  3. It doesn’t allow null key and null values.

Hierarchy of Hashtable class


It extends Dictionary and implements Map, Cloneable, Serializable interfaces in Java.

Source code of Item.java
package com.t4b.test; public class Item { String name; int id; double price; public Item(String name, int id, double price) { super(); this.name = name; this.id = id; this.price = price; } @Override public String toString() { return "Item [name=" + name + ", id=" + id + ", price=" + price + "]"; } }


Source code of TestMain.java
package com.t4b.test; import java.util.Hashtable; import java.util.Map; public class TestMain { public static void main(String[] args) { Hashtable<Integer, Item> map = new Hashtable<Integer, Item>(); map.put(1, new Item("Apple", 1, 150.0)); map.put(2, new Item("Grape", 2, 250.0)); map.put(3, new Item("Mango", 3, 10)); map.put(2, new Item("Pine Apple", 4, 100)); for (Map.Entry item : map.entrySet()) { System.out.println(item.getKey() + " : " + item.getValue()); } } }

Happy Exploring!

No comments:

Post a Comment