Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (2.6k points)

Why doesn't Set provide 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 equals method is overridden, 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 foo.

1 Answer

0 votes
by (46k points)

There would be no intent in making the element if it is equal. A Map is admirably suited for this use situation.

If you yet want to find the element you have no other choice but to apply 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);

    }

}

Related questions

0 votes
1 answer
0 votes
1 answer
asked Nov 20, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...