简体   繁体   English

Java比较集如何?

[英]How does Java compare Sets?

I have a class 我上课了

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

When I build a set Set<Foo> , it compiles and runs. 当我构建一个Set<Foo> ,它会编译并运行。 Comparing integers are simple, but how does Java compare two sets? 比较整数很简单,但Java如何比较两组?

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 这是来自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 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). Set已经定义了.equals() ,并且需要Set所有实现来按照doc所说的方式实现它(当然,它也适用于.hashCode() )。

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. 注意,合同规定元素的顺序无关紧要 ,因此[1, 2, 3][2, 1, 3]是相等的。 This is unlike List where order does matter. 这不像List ,其中为了此事

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM