简体   繁体   中英

Does .equals on Hashset return true regardless of order?

For the Hashset in java there is a .equals method comparing elements in each set. Will this return true regardless of order?

Example, let's say we have one set with elements {a,b,c} and another with elements {b,c,a}

if you use .equals on these two sets will it return true, or does it have to be sorted?

This should return true. The documentation says :

Compares the specified object with this set for equality. Returns true if the given object is also a set, the two sets have the same size, and every member of the given set is contained in this set. This ensures that the equals method works properly across different implementations of the Set interface.

Java HashSet s are unorderedthey do not have an ordering . Therefore your question simply cannot be asked as posed. The set {a,b,c} is the same as the set {b,c,a} . That said, HashSet inherit's AbstractSet#equals(Object) which tells us the following:

Compares the specified object with this set for equality. Returns true if the given object is also a set, the two sets have the same size, and every member of the given set is contained in this set. This ensures that the equals method works properly across different implementations of the Set interface.

HashSet implements the Set interface(modeling the mathematical set abstraction), which contains no order information and therefore sort makes no sense in a set. As a result, equals in a Set only considers the members and disregards the orders of members.

Yes, it will be true because a Set has no implicit order.

You can apply order to a set by using adding a Comparator, or using a special case of Set, such as TreeSet.

Incidentally, a hashcode is used for fast comparison in a Set. According to the equals contract, any two objects that are considered "equal" must have the same hashcode.

This means a Set only has to fall-back to more time consuming methods in the unlikely event of a hashcode colission.

Hash is essentially an unordered list, so yes,

if hash A contains {1,2,3,4,5}, and hash B contains {3,1,5,4,2}, then they will be equal.

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.

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