java - Is hashcode() a good way to compute an unique token from a list of informations? -


i have

hashmap<string,anobject>  

and i'd give string key value infos anobject value contains. suppose anobject made way:

public class anobject(){      public string name;      public string surname; } 

is correct assign key to:

string.valueof(o.name.hashcode()+o.surname.hashcode()); 

? or there better way compute string hash code value list?

no, absolutely not. hashcode() not guaranteed unique.

the rules of hash code simple:

  • two equal values must have same hash code
  • two non-equal values ideally have different hash codes, can have same hash code. in particular, there 232 possible values return hashcode(), more 232 possible strings, making uniqueness impossible.
  • the hash code of object should not change unless equality-sensitive aspect of changes. indeed, it's generally idea make types implementing value equality immutable, @ least in equality-sensitive aspects. otherwise can find can't entry using exact same object reference used key!

hash codes optimization technique make quick find "probably small" set of candidate values equal target, iterate through rigorous equality check find whether of them actually equal target. that's lets key in hash-based collection. key isn't hash itself.

if need create key 2 strings, you're going have make from 2 strings (with sort of delimiter can tell difference between {"a", "bc"} , {"ab", "c"} - understanding delimiter might appear in values if you're not careful).

see eric lippert's blog post on topic more information; that's based on .net rather java, apply. it's worth understanding semantics of hashcode aren't same of cryptographic hash. in particular, it's fine result of hashcode() change if start new jvm create object same fields - no-one should persisting results of hashcode. that's not case sha-256, should permanently stable particular set of data.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -