Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
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

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "HashMap prob" Watch "HashMap prob" New topic

HashMap prob

Debajit Paul

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();
ob1 = new HashTest(1);
a) one
b) two
c) three
d) null
e) Compilation fails

Why the answere is null?
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 41089
Please QuoteYourSources.

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

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

Joined: Mar 22, 2005
Posts: 41089
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 :
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%
wood burning stoves
subject: HashMap prob
Similar Threads
some questions from generics
questions on generics
hashmap doubt
Class Already Defined