javacodex.com
Java Examples
Java Examples
memu home questions

Basic HashSet Example

This java example is a basic HashSet example.

Source: (MyHashSet.java)

import java.util.HashSet;
 
public class MyHashSet {
 
   public static void main(String args[]){
 
      HashSet<String> hs = new HashSet<String>();
      hs.add("Bill");
      hs.add("Tom");
      hs.add("Harry");
      hs.add("George");
      System.out.println("Size of the set: "+ hs.size());
      System.out.println("Elements: " + hs);
      System.out.println("Removing George");
      hs.remove("George");
      System.out.println("Size of the set: " + hs.size());
      System.out.println("Elements: " +  hs);
   }
}
 

Output:

# java MyHashSet 
Size of the set: 4
Elements: [Bill, Harry, Tom, George]
Removing George
Size of the set: 3
Elements: [Bill, Harry, Tom]

Contact: javacodex@yahoo.com