簡體   English   中英

Java比較集如何?

[英]How does Java compare Sets?

我上課了

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

當我構建一個Set<Foo> ,它會編譯並運行。 比較整數很簡單,但Java如何比較兩組?

我應該覆蓋

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

或者有一組比較?

這是來自AbstractSet類的methd equals的實現,並且Set大多數實現將擴展它

  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已經定義了.equals() ,並且需要Set所有實現來按照doc所說的方式實現它(當然,它也適用於.hashCode() )。

所以你必須:

set1.equals(set2)

注意,合同規定元素的順序無關緊要 ,因此[1, 2, 3][2, 1, 3]是相等的。 這不像List ,其中為了此事

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM