Movatterモバイル変換


[0]ホーム

URL:


Open In App
Try it on GfG Practice
redirect icon

In Java, the Set interface is a part of the Java Collection Framework, located in the java.util package. It represents a collection of unique elements, meaning it does not allow duplicate values.

  • The set interface does not allow duplicate elements.
  • It can contain at most one null value except TreeSet implementation which does not allow null.
  • The set interface provides efficient search, insertion, and deletion operations.
Java
importjava.util.HashSet;importjava.util.Set;publicclassGeeks{publicstaticvoidmain(Stringargs[]){// Create a Set using HashSetSet<String>s=newHashSet<>();// Displaying the SetSystem.out.println("Set Elements: "+s);}}

Explanation: In the above example, HashSet will appear as an empty set, as no elements were added. The order of elements in HashSet is not guaranteed, so the elements will be displayed in a random order if any are added.

Hierarchy of Java Set interface

The image below demonstrates the hierarchy of Java Set interface.

set
Set-Hierarchy

Classes that implement the Set interface

  • HashSet: A set that stores unique elements without any specific order, using a hash table and allows one null element.
  • EnumSet : A high-performance set designed specifically for enum types, where all elements must belong to the same enum.
  • LinkedHashSet: A set that maintains the order of insertion while storing unique elements.
  • TreeSet: A set that stores unique elements in sorted order, either by natural ordering or a specified comparator.

Declaration of Set Interface

The declaration of Set interface is listed below:

public interface Set extends Collection 

Creating Set Objects

Since Set is aninterface, objects cannot be created of the typeset. We always need a class that implements this interface in order to create an object. And also, after the introduction ofGenerics in Java 1.5, it is possible to restrict the type of object that can be stored in the Set. This type-safe set can be defined as:

// Obj is the type of the object to be stored in Set 
Set<Obj> set = new HashSet<Obj> (); 

Performing Various Operations on Set

Set interface provides commonly used operations to manage unique elements in a collection. Now let us discuss these operations individually as follows:

1.Adding Elements

To add elements to a Set in Java, use the add() method.

Java
importjava.util.*;// Main classclassGeeks{publicstaticvoidmain(String[]args){Set<String>s=newHashSet<String>();s.add("B");s.add("B");s.add("C");s.add("A");System.out.println(s);}}

Output
[A, B, C]

2.Accessing the Elements

After adding the elements, if we wish to access the elements, we can use inbuilt methods likecontains().

Java
importjava.util.*;classGeeks{publicstaticvoidmain(String[]args){Set<String>h=newHashSet<String>();h.add("A");h.add("B");h.add("C");h.add("A");System.out.println("Set is "+h);Strings="D";System.out.println("Contains "+s+" "+h.contains(s));}}

Output
Set is [A, B, C]Contains D false

3.Removing Elements

The values can be removed from the Set using theremove() method.

Java
importjava.util.*;classGeeks{publicstaticvoidmain(String[]args){// Declaring object of Set of type StringSet<String>h=newHashSet<String>();// Elements are added using add() method, Custom input elementsh.add("A");h.add("B");h.add("C");h.add("B");h.add("D");h.add("E");System.out.println("Initial HashSet "+h);// Removing custom element using remove() methodh.remove("B");System.out.println("After removing element "+h);}}

Output
Initial HashSet [A, B, C, D, E]After removing element [A, C, D, E]

4. Iterating elements

There are various ways to iterate through the Set. The most famous one is to use the enhanced for loop.

Java
importjava.util.*;classGeeks{publicstaticvoidmain(String[]args){// Creating object of Set and declaring String typeSet<String>h=newHashSet<String>();// Adding elements to Set using add() method, Custom input elementsh.add("A");h.add("B");h.add("C");h.add("B");h.add("D");h.add("E");// Iterating through the Set via for-each loopfor(Stringvalue:h)// Printing all the values inside the objectSystem.out.print(value+", ");System.out.println();}}

Output
A, B, C, D, E,

Methods of Set Interface

Let us discuss methods present in the Set interface provided below in a tabular format below as follows:

MethodDescription
add(element)Adds element if not already present. Returns true if added.
addAll(collection)Adds all elements from the given collection.
clear()Removes all elements from the set.
contains(element)Checks if the set contains the specified element.
containsAll(collection)Checks if the set contains all elements from the given collection.
hashCode()Returns the hash code of the set.
isEmpty()This method is used to check whether the set is empty or not.
iterator()This method is used to return theiterator of the set.
remove(element)Removes the specified element from the set.
removeAll(collection)Removes all elements in the given collection from the set.
retainAll(collection)Retains only elements present in the given collection.
size()Returns the number of elements in the set.
toArray()This method is used to form an array of the same elements as that of the Set.

Set Interface In Java
Visit Courseexplore course icon
Improve

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp