java - HashMap collisions: is my code correct? -


i want have 1 datewrapper - representing date (built hibernate persistance, story) - @ existing @ same time same date.

i'm bit confused collisions , keys hashing. i'm writing factory datewrapper object, , thought use milliseconds of parsed date key i've seen others doing. but, happens if there collision?. milliseconds different 1 another, internal table may smaller long exist. , once hash map has collision, uses equals, how can distinguish 2 different object long? maybe, it's put method drop (overwrite) value i'd insert... so, code safe, or bugged??

package myproject.test;  import java.util.hashmap; import java.util.map;  import org.joda.time.datetime; import org.joda.time.format.datetimeformat; import org.joda.time.format.datetimeformatter;  import myproject.utilities.datewrapper;  public class datewrapperfactory {      static map <long, datewrapper> cache = new hashmap<long, datewrapper>();     static datetimeformatter parser =         datetimeformat.forpattern("yyyy-mm-dd");      static datewrapperfactory instance = new datewrapperfactory();      private datewrapperfactory() {     }      public static datewrapperfactory getinstance() {         return instance;     }       public static datewrapper get(string source) {         datetime d = parser.parsedatetime(source);         datewrapper dw = cache.get(d.getmillis());         if (dw != null) {             return dw;         } else {             dw = new datewrapper(d);             cache.put(d.getmillis(), dw);             return dw;         }     }  }  package myproject.test;  import org.joda.time.datetime;  public class datewrapper {      private datetime date;      public datewrapper(datetime dt) {         this.date = dt;     }  } 

if using actual objects want map keys , letting hashmap take care of details of hashcode of objects (and keys implement equals , hashcode according contract) there no issue if there's hashcode collision other possible performance reduction due need search linearly through every entry hashed same bucket.

the issue in other question subject of collisions came rather using actual object should have been key, using hashcode of object key itself. incorrect , have led incorrect behavior.... when went value given key in map, result have been value maps different key happens have same hashcode.

the moral of story is: use actual key or equivalent (like millis of datetime in case) key, not key's hashcode. hashmap needs hashcode you.


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -