Gaurav
Gaurav

Reputation: 33

hashcode() vs toString().hashcode();

Just trying to discuss and understand the difference between the below codes.

a >

SortedSet<String> set = new TreeSet<>();
set.addAll(str);
int hashcode= set.toString().hashCode();

b>

SortedSet<String> set = new TreeSet<>();
set.addAll(str);
int hashcode = set.hashCode();

I have checked if you are putting the same string element in both set in any order, hashcode return value will be the same. Just wanted to know is condition a> more secure than

Upvotes: 0

Views: 174

Answers (1)

Mureinik
Mureinik

Reputation: 311998

The first snippet converts the set to a string (a potentially heavy operation), and then hashes it. The second hashs the set directly.

Since equal sets would produce equal strings and equal hashs, both methods are technically OK, but it's really redundant to convert the set to a string first (method a) - there's no benefit in using it, and all you're doing is wasting resources on the conversion to string.

Upvotes: 3

Related Questions