Java Set
Published Apr 18, 2022
Contribute to Docs
A Set is an interface provided in the java.util package that implements collections with zero duplicate elements. Some implementations will have restrictions on the elements the Set can contain, such as excluding null elements. Adding an ineligible element will typically throw an unchecked NullPointerException or a ClassCastException.
Examples of classes implementing the Set interface are HashSet and TreeSet.
Syntax
SetClass<DataType> mySet = new SetClass<DataType> ();
The SetClass is a class that implements the Set interface, and is initialized with a generic type inside angle brackets < ... >.
Methods
The Set interface utilizes the following methods:
.add():.add(item)addsitemto theSetif it is not already present..clear(): Removes all the elements from theSet.contains():.contains(item)returnstrueifitemis a member of theSet..remove():.remove(item)will removeitemfrom theSet..size(): Returns the number of items in theSet.
Example
This is an example of a Set interface being implemented by a HashSet:
import java.util.HashSet;import java.util.Set;public class Main {public static void main(String[] args) {Set<String> food = new HashSet<String>();food.add("Cabbage");food.add("Pizza");food.add("Sausage");food.add("Potatoes");food.add("Salad");food.remove("Sausage");System.out.println(food.contains("Sausage"));System.out.println(food);System.out.println(food.size());}}
This will output the following:
false[Pizza, Potatoes, Cabbage, Salad]4
Set
- .addAll()
- Adds all of the elements in the specified collection to this set if they are not already present.
- TreeSet
- Refers to a collection that stores objects in a tree structure.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours