This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
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
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
posted
0
The get method evaluates the hashCode before evaluating equals.
If you override hashCode e.g. public int hashCode() { return (hashCode * 17) ; }
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.