Set interface in java with example

Read this article to know what is Set interface and its implemented classes in java with examples programs.  Set interface  represents a group of elements arranged as like an array. Set interface will grown dynamically when the elements are stored into it. Set will not allow duplicate elements to store into it. Set interface implemented classes are,
  • HashSet<T>
  • TreeSet<T>
  • LinkedHashSet<T>
          <T> represents the generic type of the storing element in set.

Set interface methods:
  • boolean add(Object) : Ensures the Set holds the argument. The Object is added only if it isn't already in the Set. Returns false if the Object was not added to the Set.
  • void clear() : Removes all elements from the Set.
  • boolean contains(Object) : Returns true if the Set contains the argument.
  • boolean isEmpty() : Returns true if the Set contains no elements.
  • Iterator iterator() : Returns an Iterator object which can be used to traverse through the Set. (See last month's article for information on the Iterator interface.)
  • boolean remove(Object) : Removes the argument from the Set. Returns true if the argument was removed.
  • int size() : Returns the number of elements in the Set.
  • Object[] toArray() : Returns an Object array containing all the elements in the Set.
HashSet:   
HashSet represents a set of elements (Objects). It does not guarantee the order of elements. It does not allow duplicate elements to be stored.  We can create the HashSet class as
class HashSet<T>

Here, T represents the Generic type parameter. It represents which type of elements are being stored into the HashSet .
HashSet<String> hs = new HashSet<String>();

In the above line represents the HashSet<String> object creation and it store the String type of values into it.

The HashSet doesn't add any additional methods beyond those found in the Set interface. Any object place in HashSet must implement the hashCode() and equals() methods. The HashSet default capacity is 16 and the default load factor is 0.75 . Load factor determines the point where the capacity of the HashSet would be increased internally.

Ex: Here is the example program which will shows the use of HashSet and Iterator .
package com.javatbrains.collections;

import java.util.HashSet;
import java.util.Iterator;

public class HashSetUse {

     public static void main(String[] args) {
          // Create a HashSet to store Strings
          HashSet<String> hset = new HashSet<String>();

          // Store some String elements
          hset.add("India");
          hset.add("America");
          hset.add("Pakistan");
          hset.add("India");
          hset.add("America");

          // Add iterator to hset
          Iterator<String> it = hset.iterator();

          // Display element by element using Iterator
          System.out.println("Elements using iterator:");
          while (it.hasNext()) {
              String country = (String) it.next();
              System.out.println(country);
          }
     }

}
OutPut:
     Elements using iterator:
          America
          Pakistan
          India

Steps:
  • Create HashSet object by using new operator.
  • Add some String type elements into HashSet object.
  • Create and Iterator instance by using HashSet object.
  • Get each element one by one from iterator by processing through while loop.
As of I mentioned in the above, classes that are to be stored in HashSet must implement the hashCode() and equals() methods. Here is an example.
package com.javatbrains.collections;

public class Person {
     private String aadhar;
     private String name;

     public String getName() {
          return name;
     }

     public String getAadhar() {
          return aadhar;
     }

     public boolean equals(Object obj) {
          boolean retValue = false;
          if (obj instanceof Person) {
               Person e = (Person) obj;
              retValue = aadhar.equals(e.getAadhar());
          }
          return retValue;
     }

     public int hashCode() {
          return aadhar.hashCode();
     }
}

LinkedHashSet:
This is an subclass of HashSet class and does not contain any additional members on its own.
class LinkedHashSet<T>

          Here, <T> represents the generic type parameter. It represents the data type of elements being stored into the LinkedHashSet . LinkedHashSet Internally uses a linked list to store the elements.

TreeSet:
The TreeSet class guarantees that the Objects in the Set will be sorted in ascending order by either the Object's natural order or by the Comparator provided to the constructor of the TreeSet. Searching for an item in TreeSet will be slower than in a HashSet because the " Hashing algorithm" gives better performance than the compareTo() method which is used to locate items in a TreeSet.  TreeSet added several methods to the Set interface,
  • Object first(): Gets the first element from the sorted set.
  • Object last() : Gets the last element from the sorted set.
  • SortedSet headSet(Object toElement): Returns a view of the portion of this set whose elements are less than toElement.
  • SortedSet tailSet(Object fromElement): Returns a view of the portion of this set whose elements are greater than or equal to from Element.
  • SortedSet subSet(Object fromElement, Object toElement): Returns a view of the portion of this set whose starting element is greater than or equal to from Element and whose ending element is less than toElement.
Ex: Here is the example program to show use of TreeSet and Iterator.
package com.javatbrains.collections;

import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetUse {

     public static void main(String[] args) {
          TreeSet<String> tset = new TreeSet<String>();

          // Store some String elements
          tset.add("India");
          tset.add("America");
          tset.add("Pakistan");
          tset.add("India");
          tset.add("America");

          // Add iterator to tset
          Iterator<String> it = tset.iterator();

          // Display element by element using Iterator
          System.out.println("Elements using iterator:");
          while (it.hasNext()) {
              String country = (String) it.next();
              System.out.println(country);
          }
     }

}
OutPut:
     Elements using iterator:
          America
          India
          Pakistan
         
If you have observed the output of the previous classes,   HashSetUse class doesn't give any ordered output. But, TreeSetUse.java class gives you ascending order by default.

Sorting Collections:
We have two options to sort elements in TreeSet.
  • Comparable interface
  • Comparator class
If you want to use Comparable interface, objects of the class should be implements the Comparable interface in the TreeSet . Comparable interface has single method,
int compareTo(Object o)

The compareTo() method will return a negative number, zero, or positive number depending on whether the Object is less than, equal to, or greater than the Object argument.
package com.javatbrains.collections;

public class Person implements Comparable{
     private String aadhar;
    
     public String getAadhar() {
          return aadhar;
     }

     // The comparison can be done on any field we choose.
     // For this example we have decided to sort by empNum.
     public int compareTo(Object obj) {
          Person e  = (Person)obj;
          return aadhar.compareTo(e.getAadhar( ));
     }
}

The second option is provide a Comparator for the TreeSet to use. The advantage of the Comparator is that we can create multiple Comparator  that can be used to sort our TreeSet in multiple ways.
package com.javatbrains.collections;

import java.util.Comparator;

public class Person implements Comparable {
     private String aadhar;
     private String name;

     public String getName() {
          return name;
     }

     public String getAadhar() {
          return aadhar;
     }

     public static final Comparator AADHAR_ORDER = new Comparator() {
          public int compare(Object o1, Object o2) {
              Person p1 = (Person) o1;
              Person p2 = (Person) o2;
              return p1.getAadhar().compareTo(p2.getAadhar());
          }
     };
    
     public static final Comparator NAME_ORDER = new Comparator() {
          public int compare(Object o1, Object o2) {
              Person p1 = (Person) o1;
              Person p2 = (Person) o2;
              return p1.getName().compareTo(p2.getName());
          }
     };
}

As I have mentioned in the below, I will use the above Comparator NAME_ORDER in another class to keep Person names in an order.
TreeSet ts = new TreeSet(Person.NAME_ORDER );

The same option used for TreeSet can use any of the collection. A collection can be sorted by using the static sort method of the Collections class.
Collections.sort(empArrayList);

            empArrayList – is an Arraylist object.

Comments

Popular posts from this blog

Hibernate auto increment with example

how to count the page views by using JSP

Multithreading in java with example

How to retrieve data from table by using JDBC with example

Prime, Fibonacci and Factorial number with example in java

How to insert images into database using JDBC?

How to sort list of objects in java with examples

String interview questions and answers

Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/SystemException

Store file into table by using JDBC with example