문제

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?

도움이 되었습니까?

해결책

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;
        }
    }

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top