Hi Friends, Can any one of you please explain me as how get() method works internally in HashMap class?Does it internally call equals() method to compare the key which we pass as a parameter in get()? Since it is said that Strings override equals(), they can be used as a key in hashMap, I just wanted to know if get() internally uses equals() to compare the keys to retreive the value.
If you have Java 6:- Go into your jdk folder, and you will find a file called "src.zip." Unzip that into a folder, let's call it "src," and you will find a number of subfolders, which correspond to the packages in the API. Go into java->util and you will find HashMap. If you open that you will find the get() method, and you can see that it does use equals().
If you don't use Java 6 you will have to download the source file from the Java website. Try here.
It may be implementation dependent. The JavaDoc for Map.get(Object) - which HashMap implements - says :
if this map contains a mapping from a key k to a value v such that (key==null ? k==null : key.equals(k)), then this method returns v; otherwise it returns null.
So it doesn't have to call equals(), but it does need to implement the same functionality, so i would imagine most implementations do call equals().
BTW Campbell - all versions of the JDK (at least as far back as 1.3) include a src.zip.
posted 11 years ago
Joanne, thank you. I didn't realise the src.zip file was already in the other JDKs; I always went onto the Java website to download it.
I would presume the Java text is identical for JDKs for different platforms; since the get() method of HashMap on Linux uses equals() I would have thought it uses equals() on other platforms too.
posted 11 years ago
Originally posted by Campbell Ritchie: I would presume the Java text is identical for JDKs for different platforms; since the get() method of HashMap on Linux uses equals() I would have thought it uses equals() on other platforms too.
I was referring to different implementations of the JVM, not different platforms that it runs on. The JDKs that you download from the Sun site contain Sun's implementation of the JVM, but there are others. Even Microsoft used to produce one. And I believe the Eclipse IDE uses it own version.