Friday 27 July 2012

Simple Java HashSet example


This simple Java Example shows how to use Java HashSet. It also describes how to add something to HashSet object using add method.


import java.util.HashSet;

public class SimpleHashSetExample {

 public static void main(String[] args) {

  // create object of HashSet

  HashSet hSet = new HashSet();

  /**
   * Add an Object to HashSet using boolean add(Object obj) method of Java
   * HashSet class. This method adds an element to HashSet if it is not
   * already present in HashSet. It returns true if the element was added
   * to HashSet, false otherwise.
   **/

  System.out.println("Adding 1:" + hSet.add(1));
  System.out.println("Adding 2:" + hSet.add(2));
  System.out.println("Adding 3:" + hSet.add(3));

  /**
   * Adding element 2 second time returns false, because set can't occupy
   * duplicate elements.
   **/

  System.out.println("Adding 2:" + hSet.add(2));

  System.out.println("HashSet contains.." + hSet);
 }
}


The output is:



Adding 1:true
Adding 2:true
Adding 3:true
Adding 2:false
HashSet contains..[1, 2, 3]

No comments:

Post a Comment