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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.