In Java, equals(o) tells you whether a HashSet is equal to another object. It returns true when o is also a Set, has the same size, and contains every element of this set.
The order of the elements does not matter, and the other set can be any Set implementation, such as TreeSet or LinkedHashSet. A List is never equal to a set, even with the same elements.
An instance method of java.util.HashSet (class since Java 1.2): a set of unique elements kept in a hash table, with no guaranteed order, one null element allowed, and no thread safety.
Syntax
One argument: the object to compare with.
Java
Set<String> a = new HashSet<>(Arrays.asList("x", "y"));
Set<String> b = new HashSet<>(Arrays.asList("y", "x"));
boolean same = a.equals(b); // true
Call
What it does
a.equals(b)
true if both sets hold the same elements.
a == b
true only if both variables point to the very same object.
Objects.equals(a, b)
Null-safe version of equals.
a.equals(list)
Always false: a set never equals a list.
The rule comes from the Set interface, so a HashSet equals a TreeSet with the same elements. Elements are compared with their own equals() method.
Library declarations
Java
// Inherited from java.util.AbstractSet<E>
public boolean equals(Object o)
// Contract defined by Set<E>
Parameters
Parameter
Description
o (Object)
The object to compare with. It may be null, which gives false.
Return Value
Return Value
Description
true
o is a Set of the same size that contains every element of this set.
false
o is null, is not a Set, or has different elements.
null as the argument. A set is never equal to null, so roster.equals(null) is a quiet false.
The helper agrees.Objects.equals(roster, null) is also false because exactly one side is null.
Two nulls are equal.Objects.equals(missing, null) returns true when both sides are null.
null as the receiver. Calling a method on the null variable missing throws NullPointerException; Objects.equals(a, b) avoids that by checking for null first.
Frequently Asked Questions
Call a.equals(b). It is true when both are sets of the same size containing the same elements, whatever their order.
No. Sets have no meaningful order, so equals() only checks which elements are present.
== checks whether two variables point to the same object. equals() checks whether two sets hold the same elements.
A HashSet equals any other Set with the same elements, including a TreeSet. It never equals a List, even with the same elements.
Set equality relies on the elements' own equals() and hashCode(). Without them, two sets of your own objects are equal only when they hold the very same object instances.