Frage

I have a class

class Foo
{
   int x;
   Set<Integer> set;
}

When I build a set Set<Foo>, it compiles and runs. Comparing integers are simple, but how does Java compare two sets?

Should I override as

        if(this.toBeLocalized != that.toBeLocalized)
        {
            if(this.set.size() == that.set.size())
            {
                Set<Integer> ref = new HashSet<>();
                ref.addAll(this.set);
                ref.removeAll(that.set);
                if(ref == null)
                {
                    return 0;
                }
            }
        }
        return -1;
    }

Or there is a comparison for sets?

War es hilfreich?

Lösung

this is implementation of methd equals from class AbstractSet, and most of implementations of Set will extends it

  public boolean equals(Object o) {
    if (o == this)
        return true;

    if (!(o instanceof Set))
        return false;
    Collection c = (Collection) o;
    if (c.size() != size())
        return false;
        try {
            return containsAll(c);
        } catch (ClassCastException unused)   {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }
    }

Andere Tipps

Set already defines .equals(), and all implementations of Set are required to implement it the way the doc says (and, of course, it goes for .hashCode() as well).

So you just have to:

set1.equals(set2)

Note that the contract stipulate that order of elements does not matter, so [1, 2, 3] and [2, 1, 3] are equal. This is unlike List where order does matter.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top