Topics Index

HashSetDemo - Java Example Program

import java.util.*;

class HashSetDemo
    public static void main(String arg[])
        List<Character> characters = new ArrayList<Character>(); //
        HashSet<Character> hashcharacters = new HashSet<Character>(characters); // LINE B
        System.out.println("Elements in hashcharacters: " + hashcharacters); // LINE C
        System.out.print("retrieving in order: "); // LINE D
        for (int i = 0; i < hashcharacters.size(); i++)
            System.out.print(characters.get(i) + " "); // LINE E
        hashcharacters.remove('2'); // LINE F
        System.out.print("Modified HashSet: " + hashcharacters); // LINE G    

Elements in hashcharacters: [D, 2, A, B, C]
retrieving in order: A B C D 2
Modified HashSet: [D, A, B, C]


In the above program at LINE A we have created an ArrayList characters and added elements. At LINE B we have created a HashSet hashcharacters and added all the elements of characters to hashcharacters. At LINE C we are printing the elements in the hashcharacters. We can see the output as we discussed earlier the HashSet doesn't return the values in order when we call the HasSet. At LINE D we are retrieving the elements in hashcharcters in order. At LINE E inside for loop we are printing the elements in hashcharcters in order. At LINE F we have removed the element 2 from hashcharacters. At LINE G we are displaying the modified hashcharcters.

  • Create a HahsSet with the default constructor and add all the elements of characters.
  • At LINE F remove the single quotes for 2 and see the output.
    The program doesn't show any compilation error since the parameter to be passed for the remove method is integer and method checks for the value in the set if found it removes the object if not the HashSet will remain unchanged.

© meritcampus 2019

All Rights Reserved.

Open In App