Java Collection: HashMap - BunksAllowed

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

Community


It is a specialized implementation of the Map interface. It is used to store <key, value> pairs. Hashing technique is used in HashMap implementation.

A few important facts about HashMap are as follows:

  1. It allows duplicate values.
  2. It is not synchronized.
  3. It is an ordered collection.
  4. It allows a null key, but only once.

Hierarchy of HashMap class


It extends AbstractMap and implements Map, Clonable, Srializable 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.HashMap; import java.util.Map; public class TestMain { public static void main(String[] args) { HashMap<Integer, Item> map = new HashMap<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

Note: Only a member of this blog may post a comment.