foobar foobar - 1 year ago 66
Java Question

Getting an element from a Set

Why doesn't Set povide an operation to get an element that equals another element?

Set<Foo> set = ...;
Foo foo = new Foo(1, 2, 3);
Foo bar = set.get(foo); // get the Foo element from the Set that equals foo

I can ask whether the Set contains an element equal to bar, so why can't I get that element? :(

To clarify, the
method is overriden, but it only checks one of the fields, not all. So two Foo objects that are considered equal can actually have different values, that's why I can't just use

Answer Source

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 =;
        if (f.equals(new Foo("Hello")))
            System.out.println("foo found");

static class Foo {
    String string;
    Foo(String string) {
        this.string = string;
    public int hashCode() { 
        return string.hashCode(); 
    public boolean equals(Object obj) {
        return string.equals(((Foo) obj).string);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download