*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes HashMap prob Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "HashMap prob" Watch "HashMap prob" New topic
Author

HashMap prob

Debajit Paul
Greenhorn

Joined: Mar 27, 2008
Posts: 12
import java.util.*;
public class HashTest{
int hashCode;
public HashTest(int hashCode){
this.hashCode = hashCode;
}
public boolean equals(Object other){
if(other instanceof HashTest){
return ((HashTest)other).hashCode == this.hashCode;
}
return false;
}
public static void main(String [] args) {
HashTest ob1 = new HashTest(3);
HashTest ob2 = new HashTest(2);
HashTest ob3 = new HashTest(1);
Map mp = new HashMap();
mp.put(ob1,"one");
mp.put(ob2,"two");
mp.put(ob3,"three");
ob1 = new HashTest(1);
System.out.println(mp.get(ob1));
}
}
a) one
b) two
c) three
d) null
e) Compilation fails


Why the answere is null?
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41621
    
  55
Please QuoteYourSources.


Ping & DNS - my free Android networking tools app
Debajit Paul
Greenhorn

Joined: Mar 27, 2008
Posts: 12
javabeat generic questions.....1.5
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41621
    
  55
It returns null because the object that is used as key in the "get" method does not exist as key in the HashMap. The equals method plays no part in this (it's never called).

If you comment out the "ob1 = new HashTest(1);" line, then it will return "one".
Karl Prenton
Ranch Hand

Joined: Mar 10, 2008
Posts: 51
The get method evaluates the hashCode before evaluating equals.

If you override hashCode e.g.
public int hashCode() { return (hashCode * 17) ; }

the output would be "three"

good read : http://www.javaranch.com/journal/200407/ScjpTipLine-hashCodesUncovered.html
Gary Kevin
Ranch Hand

Joined: Jul 24, 2006
Posts: 43
you can print out the hashcode of ob1 just like this:


The hashCode is different from the previous hashCode after you assign a new HashTest object.

"The hashcode value of an object is used by some collection classes.Although you can think of it as kind of an object ID number,it isn't necessarily unique.Collections such as HashMap and HashSet use the hashcode value of an object to determine how the object should be stored in the collection,and the hashcode is used again to help locate the object in the collection."


because you don't override the hashCode() method,obj1#1 and obj1#2 are in differnt "buckets", they are not equal.


SCJP 5.0 72%
 
 
subject: HashMap prob