简体   繁体   中英

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

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.

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