Given two Sets: how to compare them efficiently in Java?
List
s, sort them and compare them. (Comparable
)Set
s and compare the hashCode
of the Sets?background:
many comparisons need to be done Sets are small (usually < 5 elements per set).
The proper way to compare two sets is to use the equals
method. I would not worry about performance unless you have proven that this is a part of your code that is causing performance issue (which I doubt). And considering the size of your sets (5 elements) this will be very fast (probably sub millisecond).
keep them as lists, sort them and compare them. (comparable)
will certainly be slower as you will need to copy the elements, sort them and compare.
keep them as sets and compare the hashcode of the sets?
if 2 sets are equal (have the same content) they will have the same hashcode. The reciprocal is not true: 2 sets with different content may have the same hashcode. Also note that for a HashSet
for example, the hashcode is calculated by iterating over all the elements so it is not a free operation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With