Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently compare Sets? [duplicate]

Given two Sets: how to compare them efficiently in Java?

  • (a) keep them as Lists, sort them and compare them. (Comparable)
  • (b) keep them as Sets and compare the hashCode of the Sets?

background:

many comparisons need to be done Sets are small (usually < 5 elements per set).

like image 282
user1654885 Avatar asked Dec 20 '22 13:12

user1654885


1 Answers

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.

like image 184
assylias Avatar answered Dec 30 '22 23:12

assylias