Java Collection: HashSet - BunksAllowed

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

Random Posts


It is a specialized implementation of the Set interface. It uses the concept of HashTable in Data Structure.

A few important facts about HashSet are as follows:

  1. It is synchronized.
  2. It does not allow duplicate values.
  3. It allows null values.
  4. Element retrieval order is not the same as insertion.

Hierarchy of HashSet class


It extends AbstractSet and implements Set, Clonable, and 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.HashSet; import java.util.Iterator; public class TestMain { public static void main(String[] args) { HashSet<Item> hashset = new HashSet<Item>(); hashset.add(new Item("Apple", 1, 150.0)); hashset.add(new Item("Grape", 2, 250.0)); hashset.add(new Item("Mango", 3, 10)); hashset.add(new Item("Pine Apple", 4, 100)); Iterator<Item> itr = hashset.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } } }

Happy Exploring!

No comments:

Post a Comment