Search This Blog

Thursday 14 August 2014

Hash Set - JAVA

Hash Set in Java

Hash Set is used when simply complex objects are to be referenced in a set and when no more than only one reference to an object is needed. Hash sets are the highest performance and the simplest of the set implementations.

This program shows how to use Hash Set in Java.

Shape.java

import java.util.HashSet;

public class Shape {
 
 public static void main(String[] args){
  Shape obj1 = new Shape();
  Shape obj2 = new Circle();
  Shape obj3 = new Triangle();
  
  HashSet hashSet = new HashSet();
  //add first object to the hash set
  hashSet.add(obj1);
  System.out.println("The size of hash set is: " + hashSet.size());
  //add another object to the hash set
  hashSet.add(obj2);
  System.out.println("The size of hash set is: " + hashSet.size());
  //add another object to the hash set
  hashSet.add(obj3);
  System.out.println("The size of hash set is: " + hashSet.size());
  //Try adding already added object. It fails without giving error.
  hashSet.add(obj2);
  System.out.println("The size of hash set is: " + hashSet.size());
  //Remove one object.
  hashSet.remove(obj1);
  System.out.println("The size of hash set is: " + hashSet.size());
 }
}

Circle.java

//Circle class inherits from Shape Class
public class Circle extends Shape{
 
}

Triangle.java

//Triangle Class inherits from Shape Class
public class Triangle extends Shape {

}

No comments:

Post a Comment