Core Java Tutorial

Core Java Tutorial

Java Hashset Example Program

Java Hashset:

This class implements the Set interface.It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element(one element).
It does not allow duplicate element, it we try adding it it will replace the old data.
This class offers constant time performance for the basic operations (add, remove, contains and size)
package com.candidjava.core;
 
import java.util.HashSet;
 
public class HashSetExample {
 
  public static void main(String[] args) {
    HashSet<String> hs = new HashSet<String>();
    hs.add("hai");
    hs.add("123");
    hs.add("mathan");
    hs.add("lhs");
    hs.add("mathan");
    hs.add("lhs");
    hs.add("ramya");
    hs.add("suji");
    hs.add("ravathi");
    hs.add("sri");
 
    System.out.println("HashSet ..  " + hs);
    System.out.println("size ... " + hs.size());
    System.out
        .println("Output will be in random order and dupliate will be removed");
 
  }
 
}
Output:
HashSet ..  [hai, 123, ramya, ravathi, lhs, suji, mathan, sri]
size ... 8
Output will be in random order and dupliate will be removed