This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

This article, the original problem: translate for stackoverflow question stackoverflow.com/questions/7…

Issue an overview

Why doesn’t set provide an operation on the GET element, just like any other 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
Copy the code

I want to ask does set contain one, so I can’t get the corresponding element?

To clarify, the equals method has been overridden, but it only checks one field, not all. So two Foo objects that are considered equal can actually have different values, which is why I can’t just use Foo.

Most likes

There is no such operation for the GET element. Map would be more appropriate for this application scenario

If you still want to find an equal element, you have no choice but to use the iterator as follows:

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(a) { 
        return string.hashCode(); 
    }
    @Override
    public boolean equals(Object obj) {
        returnstring.equals(((Foo) obj).string); }}Copy the code

Other answer

If you have an equal element, why do you need to take it out of the set, if this is just equal to a key Map it would be better if you could do that anyway

Foo getEqual(Foo sample, Set<Foo> all) {
  for (Foo one : all) {
    if (one.equals(sample)) {
      returnone; }}return null;
}
Copy the code

Or use a Java8 line

return all.stream().filter(sample::equals).findAny().orElse(null);

Copy the code