🌐
W3Schools
w3schools.com › java › java_set.asp
Java Set
close() delimiter() findInLine() findWithinHorizon() hasNext() hasNextBoolean() hasNextByte() hasNextDouble() hasNextFloat() hasNextInt() hasNextLine() hasNextLong() hasNextShort() locale() next() nextBoolean() nextByte() nextDouble() nextFloat() nextInt() nextLine() nextLong() nextShort() radix() reset() useDelimiter() useLocale() useRadix() Java File Methods Java FileInputStream Java FileOutputStream Java BufferedReader Java BufferedWriter Java Iterator Methods Java Collections Methods Java System Methods Java Errors & Exceptions · Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Practice Problems Java Server Java Syllabus Java Study Plan Java Interview Q&A ... The Set interface is part of the Java Collections Framework and is used to store a collection of unique elements.
🌐
GeeksforGeeks
geeksforgeeks.org › java › set-in-java
Set in Java - GeeksforGeeks
Explanation: The third example demonstrates how to remove an element from a Set using the remove() method. The duplicate "B" is stored only once, and remove("B") removes that element from the set. There are various ways to iterate through the Set. The most famous one is to use the enhanced for loop. ... import java.util.*; class Geeks { public static void main(String[] args) { // Creating object of Set and declaring String type Set<String> h = new HashSet<String>(); // Adding elements to Set using add() method, Custom input elements h.add("A"); h.add("B"); h.add("C"); h.add("B"); h.add("D"); h.add("E"); // Iterating through the Set via for-each loop for (String value : h) // Printing all the values inside the object System.out.print(value + ", "); System.out.println(); } }
Published: 2 weeks ago
People also ask

Why do we use Set in Java?
We use Set when we want to store unique elements, such as user IDs, product codes, or distinct keywords.
🌐
wscubetech.com
wscubetech.com › resources › java › set
Set Interface in Java: Methods, Examples & Uses
How to use Set Interface in Java?
Since Set is an interface, you cannot directly create its object. Instead, you use its implementations like HashSet, LinkedHashSet, or TreeSet.
🌐
wscubetech.com
wscubetech.com › resources › java › set
Set Interface in Java: Methods, Examples & Uses
Is Set ordered in Java?
Not always. HashSet is unordered, LinkedHashSet preserves insertion order, and TreeSet keeps elements sorted.
🌐
wscubetech.com
wscubetech.com › resources › java › set
Set Interface in Java: Methods, Examples & Uses
🌐
Tutorialspoint
tutorialspoint.com › java › java_set_interface.htm
Java - Set Interface
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) {} } }
🌐
WsCube Tech
wscubetech.com › resources › java › set
Set Interface in Java: Methods, Examples & Uses
August 12, 2026 - Master Java Set Interface with easy examples. Learn Set methods, types, HashSet, LinkedHashSet, TreeSet, features, uses and common operations in Java. Read now.
🌐
CodeGym
codegym.cc › java blog › java collections › java set
Java Set
February 13, 2025 - Set<Integer> intSet = new HashSet<>(); Set<String> vSet = new HashSet<>(); Set mySet = new LinkedHashSet(); HashSet<String> myHashset = new HashSet<>(); Here is a simple example, where we create 2 Sets, HashSet and LinkedHashSet, and add into ...
🌐
Programiz
programiz.com › java-programming › set
Java Set Interface
import java.util.Set; import java.util.HashSet; class Main { public static void main(String[] args) { // Creating a set using the HashSet class Set<Integer> set1 = new HashSet<>(); // Add elements to the set1 set1.add(2); set1.add(3); System.out.println("Set1: " + set1); // Creating another set using the HashSet class Set<Integer> set2 = new HashSet<>(); // Add elements set2.add(1); set2.add(2); System.out.println("Set2: " + set2); // Union of two sets set2.addAll(set1); System.out.println("Union is: " + set2); } }
🌐
Scientech Easy
scientecheasy.com › home › blog › set in java
Set in Java - Scientech Easy
May 12, 2025 - Example 3: Let’s write a Java program in which we will search an element in set. The contains() method checks whether an element is present in the set.
🌐
Oracle
docs.oracle.com › javase › tutorial › collections › implementations › set.html
Set Implementations (The Java™ Tutorials > Collections > Implementations)
All mutative operations, such as add, set, and remove, are implemented by making a new copy of the array; no locking is ever required. Even iteration may safely proceed concurrently with element insertion and deletion. Unlike most Set implementations, the add, remove, and contains methods require time proportional to the size of the set.
Find elsewhere
Top answer
1 of 16
58

Set and Get methods are a pattern of data encapsulation. Instead of accessing class member variables directly, you define get methods to access these variables, and set methods to modify them. By encapsulating them in this manner, you have control over the public interface, should you need to change the inner workings of the class in the future.

For example, for a member variable:

Integer x;

You might have methods:

Integer getX(){ return x; }
void setX(Integer x){ this.x = x; }

chiccodoro also mentioned an important point. If you only want to allow read access to the field for any foreign classes, you can do that by only providing a public get method and keeping the set private or not providing a set at all.

2 of 16
22

I want to add to other answers that setters can be used to prevent putting the object in an invalid state.

For instance let's suppose that I've to set a TaxId, modelled as a String. The first version of the setter can be as follows:

private String taxId;

public void setTaxId(String taxId) {
    this.taxId = taxId;
}

However we'd better prevent the use to set the object with an invalid taxId, so we can introduce a check:

private String taxId;

public void setTaxId(String taxId) throws IllegalArgumentException {
    if (isTaxIdValid(taxId)) {
        throw new IllegalArgumentException("Tax Id '" + taxId + "' is invalid");
    }
    this.taxId = taxId;
}

The next step, to improve the modularity of the program, is to make the TaxId itself as an Object, able to check itself.

private final TaxId taxId = new TaxId()

public void setTaxId(String taxIdString) throws IllegalArgumentException {
    taxId.set(taxIdString); //will throw exception if not valid
}

Similarly for the getter, what if we don't have a value yet? Maybe we want to have a different path, we could say:

public String getTaxId() throws IllegalStateException {
    return taxId.get(); //will throw exception if not set
}
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-set
Java Set – Set in Java | DigitalOcean
Technical tutorials, Q&A, events — This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.
🌐
Codecademy
codecademy.com › docs › java › set
Java | Set | Codecademy
April 18, 2022 - The Set interface utilizes the following methods: .add() : .add(item) adds item to the Set if it is not already present. .clear() : Removes all the elements from the Set · .contains() : .contains(item) returns true if item is a member of the Set.
🌐
Oracle
docs.oracle.com › javase › tutorial › collections › interfaces › set.html
The Set Interface (The Java™ Tutorials > Collections > Interfaces)
The iterator method returns an Iterator over the Set. The following program prints out all distinct words in its argument list. Two versions of this program are provided. The first uses JDK 8 aggregate operations. The second uses the for-each construct. ... import java.util.*; import java.util.stream.*; public class FindDups { public static void main(String[] args) { Set<String> distinctWords = Arrays.asList(args).stream() .collect(Collectors.toSet()); System.out.println(distinctWords.size()+ " distinct words: " + distinctWords); } }
🌐
Redisson
redisson.pro › glossary › java-set.html
What is a Java set? | Redisson
In Redisson, Java sets are implemented using the RSet interface. Below is an example of how to use RSet in Redisson: RSet<SomeObject> set = redisson.getSet("anySet"); set.add(new SomeObject()); set.remove(new SomeObject()); RSet includes all of the familiar methods from the java.util.Set standard implementation, as well as Redis set functionality such as set difference, intersection, and union.
🌐
Simplilearn
simplilearn.com › home › resources › software development › set in java: the methods and operations you can perform
Set in Java: The Methods and Operations You Can Perform
August 3, 2026 - The set in Java is an interface available in the java.util package. In this article, you will learn everything about set, its operations, methods and more.
Address: 5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
🌐
o7planning
o7planning.org › 13453 › java-set
Java Set Tutorial with Examples | o7planning.org
CopyOnWriteArraySet directly compares 2 elements via their equals method. Take a look at the 2 examples CopyOnWriteArraySetDupTest1 & CopyOnWriteArraySetDupTest2 below to understand more about the above description. CopyOnWriteArraySetDupTest1.java · package org.o7planning.set.test; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; public class CopyOnWriteArraySetDupTest1 { public static class Employee { private int empId; private String empName; public Employee(int empId, String empName) { this.empId = empId; this.empName = empName; } public int getEmpId() { return empId; } public String getEmpName() { return empName; } // Employee class uses equals(Object) method inherited from Object class.
🌐
Software Testing Help
softwaretestinghelp.com › home › java › set interface in java: java set tutorial with examples
Set Interface In Java: Java Set Tutorial With Examples
May 14, 2025 - The set interface does not have any new methods defined, but it uses the methods of the Collector interface and only adds implementation to prohibit duplicate values. The set allows at most one null value. In our subsequent tutorials, we will discuss specific implementations of the Set interface, like HashSet and TreeSet. ... Thanks for your feedback! ... This tutorial explains the concept of Comparable And Comparator Interfaces In Java with examples.
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.base › java › util › Set.html
Set (Java SE 11 & JDK 11 )
January 20, 2026 - This method acts as bridge between array-based and collection-based APIs. ... Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array. If the set fits in the specified array, it is returned therein.
🌐
Medium
medium.com › @nakulmitra2114 › java-set-interface-hashset-linkedhashset-and-treeset-082d073bc27c
Java Set Interface: HashSet, LinkedHashSet, and TreeSet | by Nakul Mitra | Medium
November 5, 2024 - HashSet is a commonly used implementation of the Set interface backed by a hash table. HashSet provides constant time performance (O(1)) for basic operations, like add, remove, and contains, assuming hash functions distribute elements properly across the table. No guaranteed order: Elements are stored in no specific order. Allows null: HashSet permits one null element. Fast lookups: Offers quick lookups due to hash-based storage. ... import java.util.HashSet; public class HashSetExample { public static void main(String[] args) { HashSet<Integer> numbers = new HashSet<>(); numbers.add(1); numbers.add(2); numbers.add(1); // Duplicate, will not be added System.out.println("HashSet: " + numbers); // Output: [1, 2] System.out.println("Contains 1?
🌐
Baeldung
baeldung.com › home › java › java collections › set operations in java
Set Operations in Java | Baeldung
May 5, 2026 - Since a Set doesn’t provide an index-based get(i) method, we have to use different strategies. It’s important to remember that these strategies work best with ordered implementations, such as LinkedHashSet or TreeSet, to ensure the resulting subset contains a predictable sequence of elements. The most modern and readable way to create a subset in native Java is using the Stream API.
🌐
YouTube
youtube.com › watch
Set and HashSet in Java - Full Tutorial
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.