HashSet Example addAll containAll retainAll Iterator


Two programs are given on HashSet with different functionality.

  1. HashSet General: In this program, the general methods like contains, equals, add, size, remove, toArray and hashCode usage is illustrated. Elements are printed with foreach loop.
  2. HashSet Operations: In this program, Iterator for printing the elements of HashSet is used. The methods like addAll(), clear(), retainAll(), containsAll() and toString() are used.

It is the second of the above two. Two generics hash sets are created that stores only strings and integers.

Note: It advised to get acquainted with the methods of HashSet, constructors and the super classes before going through this program. A complete tutorial is available at HashSet Tutorial.

HashSet Example
import java.util.*;
public class HashSetOperations
{
  public static void main(String args[])
  {
    String cities[] = { "Hyderabad", "Noida", "Bangaluru", "Mumbai", "Pune" };
    List myList = Arrays.asList(cities);
    HashSet hs1 = new HashSet(myList);
    System.out.println("Elements of hs1: " + hs1);

    HashSet hs2 = new HashSet();
    hs2.addAll(hs1);
    System.out.println("Elements of hs2: " + hs2);

    System.out.println("Elements of hs1 and hs2 are same with containsAll(): " + hs1.containsAll(hs2));

    HashSet hs3 = new HashSet();
    hs3.add("Hyderabad");
    hs3.add("Mumbai");
    hs2.retainAll(hs3);
    System.out.println("\nElements of hs2 after retainAll(): " + hs2);

    String str = hs2.toString();
    System.out.println("\nElements of hs2 in string form: " + str);

    System.out.println("\nElements of hs2 before clear(): " + hs2);
    hs2.clear();
    System.out.println("Elements of hs2 after clear(): " + hs2);

		                 // PRINTING ELEMENTS WITH ITERATOR
    System.out.print("Elements of hs3 with iterator: ");
    Iterator it1 = hs3.iterator();
    while(it1.hasNext())
    {
      System.out.print(it1.next() + " ");
    }
  }
}

HashSet Example

       String cities[] = { "Hyderabad", "Noida", "Bangaluru", "Mumbai", "Pune" };
       List myList = Arrays.asList(cities);
       HashSet hs1 = new HashSet(myList);

The above code illustrates how to convert an array into a data structure. A string array cities is created and its elements are passed to List using asList() method of Arrays. Again List elements are passed to HashSet constructor. Now the generics HashSet object hs1 contains the elements of the array cities. In the previous program, HashSet General, you have seen how to convert a data structure to an array using toArray() method. This is how the designers made all the data structures interoperable with arrays. It is a very good designing aspect with which programmer feels easy to write the code.

       HashSet hs2 = new HashSet();
       hs2.addAll(hs1);
       System.out.println("Elements of hs1 and hs2 are same with containsAll(): " +  hs1.containsAll(hs2));

With a single stroke, all the elements of hs1 are added to hs2 with addAll() method, inherited from Collection interface. The containsAll() method checks their equality, whether both hash sets have the same elements are not. As hs1 and hs2 contain the same elements, the containsAll() method returned true. See the screenshot. The equality is checked in two ways in the previous program, HashSet General, in two ways – hash code and equals().

       HashSet hs3 = new HashSet();
       hs3.add("Hyderabad");
       hs3.add("Mumbai");
       hs2.retainAll(hs3);

A hash set object hs3 is created storing two elements "Hyderabad" and "Mumbai". hs2 contains many elements other than what are present in hs3. If the programmer would like to have the same elements in both hs2 and hs3, he can go for retainAll() method, inherited from Collection interface. retainAll() method deletes all the elements from hs2 that are not present in hs3 (retains only the elements of hs3).

       String str = hs2.toString();

All the elements of data structure can be converted into a string using toString() method of Object class. Now str can be used wherever hs2 is required as string as in the case displaying the elements in a text field. TextField constructor requires a string as parameter.

       hs2.clear();

The clear() method, inherited from Collection interface, deletes all the elements of the data structure. If the size() method is called, it prints 0.

       Iterator it1 = hs3.iterator();
       while(it1.hasNext())
       {
         System.out.print(it1.next() + " ");
       }

The iterator() method, inherited from Collection interface, returns an object of Iterator it1 that contains all the methods of hs3. Using hasNext() and next() methods, all the elements are printed. Iterator is fail-fast and is best explained in Interface Iterator.

Pass your comments on this tutorial HashSet Example.

1 thought on “HashSet Example addAll containAll retainAll Iterator”

  1. sir i have doubt about on HashSet ,

    HashSet hs=new HashSet();
    Student S1=new Student(67);
    Student S2=new Student(67);

    class Student
    {
    private int id;

    Student(id)
    {
    this.is=id;
    }
    public boolean equals(Object o){

    }

    public toString(){
    }
    public int hashCode(){
    }
    }

    hs.add(s1);
    hs.add(s2);
    When i am adding student object to HashSet ,hashSet add() internally calls equals(),hashCode()

    but i Override equals(),hashCode() in Student .hashset Ignores Student Equals ,hashcode method
    but why
    can u plz tel me

Leave a Comment

Your email address will not be published.