To answer the precise question "Why doesn't Set provide an operation to get an element that equals another element?", the answer would be: because the designers of the collection framework were not very forward looking. They didn't anticipate your very legitimate use case, naively tried to "model the mathematical set abstraction" (from the javadoc) and simply forgot to add the useful get() method.

Now to the implied question "how do you get the element then": I think the best solution is to use a Map<E,E> instead of a Set<E>, to map the elements to themselves. In that way, you can efficiently retrieve an element from the "set", because the get() method of the Map will find the element using an efficient hash table or tree algorithm. If you wanted, you could write your own implementation of Set that offers the additional get() method, encapsulating the Map.

The following answers are in my opinion bad or wrong:

"You don't need to get the element, because you already have an equal object": the assertion is wrong, as you already showed in the question. Two objects that are equal still can have different state that is not relevant to the object equality. The goal is to get access to this state of the element contained in the Set, not the state of the object used as a "query".

"You have no other option but to use the iterator": that is a linear search over a collection which is totally inefficient for large sets (ironically, internally the Set is organized as hash map or tree that could be queried efficiently). Don't do it! I have seen severe performance problems in real-life systems by using that approach. In my opinion what is terrible about the missing get() method is not so much that it is a bit cumbersome to work around it, but that most programmers will use the linear search approach without thinking of the implications.

Answer from jschreiner on Stack Overflow
Top answer
1 of 16
486

To answer the precise question "Why doesn't Set provide an operation to get an element that equals another element?", the answer would be: because the designers of the collection framework were not very forward looking. They didn't anticipate your very legitimate use case, naively tried to "model the mathematical set abstraction" (from the javadoc) and simply forgot to add the useful get() method.

Now to the implied question "how do you get the element then": I think the best solution is to use a Map<E,E> instead of a Set<E>, to map the elements to themselves. In that way, you can efficiently retrieve an element from the "set", because the get() method of the Map will find the element using an efficient hash table or tree algorithm. If you wanted, you could write your own implementation of Set that offers the additional get() method, encapsulating the Map.

The following answers are in my opinion bad or wrong:

"You don't need to get the element, because you already have an equal object": the assertion is wrong, as you already showed in the question. Two objects that are equal still can have different state that is not relevant to the object equality. The goal is to get access to this state of the element contained in the Set, not the state of the object used as a "query".

"You have no other option but to use the iterator": that is a linear search over a collection which is totally inefficient for large sets (ironically, internally the Set is organized as hash map or tree that could be queried efficiently). Don't do it! I have seen severe performance problems in real-life systems by using that approach. In my opinion what is terrible about the missing get() method is not so much that it is a bit cumbersome to work around it, but that most programmers will use the linear search approach without thinking of the implications.

2 of 16
149

There would be no point of getting the element if it is equal. A Map is better suited for this usecase.


If you still want to find the element you have no other option but to use the iterator:

public static void main(String[] args) {

    Set<Foo> set = new HashSet<Foo>();
    set.add(new Foo("Hello"));

    for (Iterator<Foo> it = set.iterator(); it.hasNext(); ) {
        Foo f = it.next();
        if (f.equals(new Foo("Hello")))
            System.out.println("foo found");
    }
}

static class Foo {
    String string;
    Foo(String string) {
        this.string = string;
    }
    @Override
    public int hashCode() { 
        return string.hashCode(); 
    }
    @Override
    public boolean equals(Object obj) {
        return string.equals(((Foo) obj).string);
    }
}
🌐
Medium
medium.com › javarevisited › how-to-get-an-item-from-a-set-in-java-c6c82de729ab
How to get an item from a Set in Java | Javarevisited
January 10, 2026 - The Set interface in Java does not have a get method. This has been the case since the Set interface was added in Java 2.
Discussions

class - What is the use of get and set in java.And where should it be used? - Stack Overflow
I am a beginner in Java.I recently came across it in java.I am trying to making a login form and I am trying to use get and set for it.I have classes for username And password verification I also h... More on stackoverflow.com
🌐 stackoverflow.com
Set and Get Methods in java? - Stack Overflow
How can I use the set and get methods, and why should I use them? Are they really helpful? And also can you give me examples of set and get methods? More on stackoverflow.com
🌐 stackoverflow.com
java - Should "Set" have a Get method? - Software Engineering Stack Exchange
I haven't found any language that supports get from a set so far. All "common" languages I know (Java, C#, Python, Scala, Haskell...) seem to be designed in the same way: you can add items, but you cannot retrieve them. Is there any good reason why all these languages do not support something ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
November 1, 2016
Need help understanding "get" and "set" methods in Java.
Getters and Setters are ways of allowing another class to modify member variables of an object without giving them direct access to the variables. The simplest form of them tend to be fairly redundant: public class SampleClass { private int memberInt; public int getMemberInt() { return this.memberInt; } public void setMemberInt(int x) { this.memberInt = x; } } In this form having a getter and a setter for the int seems weird, but if you decided to do a refactor and suddenly memberInt changed, you wouldn't have to go and change every place it was referenced - you can just change what the getter and setter do. It also means that you can do things before returning the value/setting the member. If you want some other value to change every time memberInt changes you can just add that into setMemberInt. The main purpose of getters and setters is encapsulation. The goal is for each class to have to know as little as possible about other classes. If I write another class that needs SampleClass int, I shouldn't need to know how SampleClass implements it. I shouldn't care if it's stored or if it's recalculated every time it's needed, and if the underlying logic behind that value changes I shouldn't need to care unless if affects the values I receive. More on reddit.com
🌐 r/learnprogramming
23
49
February 26, 2013
🌐
Educative
educative.io › answers › what-are-the-get-and-set-methods-in-java
What are the get and set methods in Java?
Set: Sets the value of the private variable. Get: Returns the value of the private variable.
🌐
W3Schools
w3schools.com › java › java_encapsulation.asp
Java Encapsulation and Getters and Setters
The get method returns the variable value, and the set method sets the value.
🌐
GeeksforGeeks
geeksforgeeks.org › java › set-in-java
Set in Java - GeeksforGeeks
Set interface is a part of the Java Collection Framework, located in the java.util package.
Published: 2 weeks ago
🌐
GeeksforGeeks
geeksforgeeks.org › java › getter-and-setter-in-java
Getter and Setter in Java - GeeksforGeeks
June 22, 2023 - For the program's convenience, the getter starts with the word "get" followed by the variable name. Setter in Java: While Setter sets or updates the value (mutators). It sets the value for any variable used in a class's programs.
🌐
Stack Overflow
stackoverflow.com › questions › 38433458 › what-is-the-use-of-get-and-set-in-java-and-where-should-it-be-used
class - What is the use of get and set in java.And where should it be used? - Stack Overflow
GET and SET are methods that can be invoked by an object the set prefix is usually used in methods that set a value to an object's attribute and the get method does the opposite of that it gets the value of the attribute that you have set on ...
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
}
Top answer
1 of 7
68

The problem here isn't that HashSet lacks a Get method, it's that your code makes no sense from the perspective of the HashSet type.

That Get method is effectively, "get me this value , please", to which the .NET framework folk would sensibly reply, "eh? You already have that value <confused face />".

If you want to store items and then retrieve them based on matching another slightly different value, then use Dictionary<String, MyClass> as you can then do:

var mset = new Dictionary<String, MyClass>();
mset.Add("Hello", new MyClass {A = "Hello", B = "Bye"});

var item = mset["Hello"];
Console.WriteLine(item.B); // will print Bye

The information of equality leaks from the encapsulated class. If I wanted to change the set of properties involved in Equals, I would have to change the code outside MyClass...

Well yes, but that's because MyClass runs amok with the principle of least astonishment (POLA). With that equality functionality encapsulated, it is completely reasonable to assume that the following code is valid:

HashSet<MyClass> mset = new HashSet<MyClass>();
mset.Add(new MyClass {A = "Hello", B = "Bye"});

if (mset.Contains(new MyClass {A = "Hello", B = "See you"})) 
{
    // this code is unreachable.
}

To prevent this, MyClass needs to be clearly documented as to its odd form of equality. Having done that, it's no longer encapsulated and changing how that equality works would break the open/closed principle. Ergo, it shouldn't change and therefore Dictionary<String, MyClass> is a good solution for this odd requirement.

2 of 7
26

You already have the item that is "in" the set - you passed it as the key.

"But it isn't the instance that I called Add with" - Yes, but you specifically claimed that they were equal.

A Set is also a special case of a Map|Dictionary, with void as the value type (well the useless methods are not defined, but that doesn't matter).

The data structure you are looking for is a Dictionary<X, MyClass> where X somehow gets the As out of the MyClasses.

The C# Dictionary type is nice in this regard, as it allows you to supply an IEqualityComparer for the keys.

For the example given, I would have the following:

public class MyClass {
   public string A {get; set;}
   public string B {get; set;}
}

public class MyClassEquivalentAs : IEqualityComparer<MyClass>{
   public override bool Equals(MyClass left, MyClass right) {
        if (Object.ReferenceEquals(left, null) && Object.ReferenceEquals(right, null))
        {
            return true;
        }
        else if (Object.ReferenceEquals(left, null) || Object.ReferenceEquals(right, null))
        {
            return false;
        }
        return left.A == right.A;
   }

   public override int GetHashCode(MyClass obj) {
        return obj?.A != null ? obj.A.GetHashCode() : 0;
   }
}

Used thusly:

var mset = new Dictionary<MyClass, MyClass>(new MyClassEquivalentAs());
var bye = new MyClass {A = "Hello", B = "Bye"};
var seeyou = new MyClass {A = "Hello", B = "See you"};
mset.Add(bye);

if (mset.Contains(seeyou)) {
    //something
}

MyClass item = mset[seeyou];
Console.WriteLine(item.B); // prints Bye
🌐
Reddit
reddit.com › r/learnprogramming › need help understanding "get" and "set" methods in java.
r/learnprogramming on Reddit: Need help understanding "get" and "set" methods in Java.
February 26, 2013 -

I am really struggling with understanding how get and set methods work. Could someone explain it to me or direct me somewhere that has good, solid, and unfortunately simple explanations on how they work. Thanks in advance!

🌐
freeCodeCamp
freecodecamp.org › news › java-getters-and-setters
Getters and Setters in Java Explained
January 25, 2020 - By convention, getters start with the word "get" and setters with the word "set", followed by a variable name.
Top answer
1 of 2
12
Rather than just giving access to a variable directly, you can use a method that retrieves the value (the getter), and another that alters the value (the setter). There are a couple reasons you might want to do this. The biggest one is control. If you just have a public variable, anything outside the class can do whatever it wants, even if it isn't technically "right" (like giving something a negative length, as an example). With the getter/setter methods, you can program extra logic to ensure that you have correct values (like throwing an exception if you try to use a negative length). You can also only provide a getter if you wanted, effectively making it so that the variable can only be read, not directly altered (at least outside the class). Another reason is to hide implementation details. If your class is storing time, as an example, you can have setters and getters for time in minutes, time in hours, time in seconds, etc. These getters and setters can use calculations to translate the units between minutes/hours/etc. to whatever is being used by the internal variable, rather than just sticking with one and remembering that the variable is in milliseconds or something. Alternatively, the "internal variable" can just not exist, like the getArea() method of a Rectangle class (meaning you only need to store length and width; though there are optimizations you can do by storing area too, and having the setters for length/width recalculate as needed). Another reason is logging. You can have your getters and setters record the fact that a retrieval or alteration occurred, giving you an easy way to debug (rather than having to find every single place you messed with a particular variable). Getters/setters can also be changed by inheritance, given that they are methods. And even if you aren't doing anything special right now, it is a good idea to have them in case you come back and find that you need to change the logic to use getters/setters. It is a lot easier to add special getter/setter functionality when you are already using them, as opposed to looking for every variable use. ------------------------------ Edit: TL;DR: In Java, a getter is just a method that gets some value (usually from a variable), while a setter is just a method that sets the value of a variable. They have advantages over just accessing the variable directly, since you can add additional logic as needed, like enforcing proper values, logging, etc.
2 of 2
9
u/Ellisander 's explanation is good. I want to clarify one thing, though. A lot of things in programming, like loops, are tools to help you to get the computer to do things. However, some features of programming language are the opposite: they're not there to help you make the computer do something, they're there to help you organize your program better. Programmers have found, through experience, that as programs get larger, if you make all of the variables public then it tends to lead to lots of bugs. Basically if you let any part of the program change anything at any time, it becomes difficult to manage. Not difficult for the computer! The computer literally doesn't care. It's difficult for you, and other programmers who need to read your code. Getters and setters are one tool to help manage the chaos. You don't HAVE to use them, but it's good practice for larger projects.
🌐
iO Flood
ioflood.com › blog › getter-and-setter-in-java
Getter and Setter in Java: Your Ultimate Guide
February 29, 2024 - For example, a setter might be used to update the text of a label, while a getter could be used to retrieve the current value of a text field. When working with databases in Java, getters and setters can be used to handle the data that’s being read from or written to the database.
🌐
Baeldung
baeldung.com › home › java › java collections › how to get first item from a java set
How to Get First Item From a Java Set | Baeldung
June 27, 2025 - A Java Set is unordered by definition, however, there are implementations that do maintain order, such as LinkedHashSet, which we’ll focus on here. We can retrieve the first element in a Set using an Iterator. The Set interface allows us to ...
🌐
CodeGym
codegym.cc › java blog › methods in java › getters and setters
Getters and Setters Methods in Java
July 23, 2024 - Cat cat = new Cat(); cat.name = ""; Here we are directly accessing the name field and setting its value. We need to somehow protect our data from improper external interference. What do we need to do that? First, all instance variables (fields) must be marked with the private modifier. Private is the strictest access modifier in Java.
🌐
YouTube
youtube.com › alex lee
Getters and Setters - Learn Getters and Setters in Java - YouTube
Full Java course: https://course.alexlorenlee.com/courses/learn-java-fast I recommend installing Codota autocomplete on your IDE (free): https://www.codota.c
Published: November 21, 2019
Views: 99K
🌐
Reddit
reddit.com › r/learnprogramming › [java] why use a "get" and "set" method?
r/learnprogramming on Reddit: [Java] Why use a "get" and "set" method?
May 3, 2013 -

I've noticed, while looking over other people's code, that they use a "get" and "set" method to access a static member of a class (typically int, float, doubles, and strings). I'm wondering why? Wouldnt it be just as effective to access it by simply referencing that specific variable?

An example:

public class A {
    public static int p = 0;
    public static int getVarP() {
        return p;
    }

    public static void setVarP(int i) {
        p = i; 
    }

class B {
    public static int n = A.getVarP;
    public B() { 
        A.setVarP(n);
    }
}

So why not just say

public static int n = A.p;

Is this just something that people do just because others do it? Or is there a specific reason?