Course
Set Interface
Java Tutorial
This Java tutorial is tailored for newcomers, offering a journey from basic principles to complex Java programming techniques. Completing this tutorial equips you with a solid understanding of Java, preparing you for advanced learning. You'll emerge ready to tackle the challenges of becoming a top-tier software engineer, with the skills to innovate and excel in the vast world of software development.
Set Interface
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.
The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.
Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ.
Set Interface Methods
The methods declared by Set are summarized in the following table
Set Interface Examples
Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet. Below are some of the implementations of the Set interface in Java.
Example to Implement Set Using HashSet
Following is an example to explain Set functionality using HashSet
import java.util.HashSet;import java.util.Set;
public class SetDemo {
public static void main(String args[]) { int count[] = {34, 22,10,60,30,22}; Set<Integer> set = new HashSet<>(); try { for(int i = 0; i < 5; i++) { set.add(count[i]); } System.out.println(set); } catch(Exception e) {} }}
Output
[34, 22, 10, 60, 30]
Example to Implement Set Using TreeSet
Following is an example to explain Set functionality using TreeSet
import java.util.HashSet;import java.util.Set;import java.util.TreeSet;
public class SetDemo {
public static void main(String args[]) { int count[] = {34, 22,10,60,30,22}; Set<Integer> set = new HashSet<>(); try { for(int i = 0; i < 5; i++) { set.add(count[i]); } System.out.println(set);
TreeSet<Integer> sortedSet = new TreeSet<>(set); System.out.println("The sorted list is:"); System.out.println(sortedSet);
System.out.println("The First element of the set is: "+ (Integer)sortedSet.first()); System.out.println("The last element of the set is: "+ (Integer)sortedSet.last()); } catch(Exception e) {} }}
Output
[34, 22, 10, 60, 30]The sorted list is:[10, 22, 30, 34, 60]The First element of the set is: 10The last element of the set is: 60
Example to Implement Set Using LinkedHashSet
Following is an example to explain Set functionality using LinkedHashSet opearations
import java.util.LinkedHashSet;import java.util.Set;
public class SetDemo {
public static void main(String args[]) { int count[] = {34, 22,10,60,30,22}; Set<Integer> set = new LinkedHashSet<>(); try { for(int i = 0; i < 5; i++) { set.add(count[i]); } System.out.println(set); } catch(Exception e) {} }}
Output
[34, 22, 10, 60, 30]