SCJP 5.0 - JavaRanch FAQ - Java Beginners FAQ - SCJP FAQ - SCJP Mock Tests - Tutorial - JavaSE7 - JavaEE6 -Generics FAQ - JLS - JVM Spec - Java FAQs - Smart Questions
SCJP 5.0 - JavaRanch FAQ - Java Beginners FAQ - SCJP FAQ - SCJP Mock Tests - Tutorial - JavaSE7 - JavaEE6 -Generics FAQ - JLS - JVM Spec - Java FAQs - Smart Questions
Meghna Bhardwaj wrote:HI ,
I am reviewing Maps from k&B , on Pg 563. It mentions that Classes used as part of the key for Maps must override equals and hashCode
method. If you do not then program will compile and run you just wont find your stuff. I just wrote a program which contradicts this!!
SCJP 6 - SCJD - SCWCD 5 - SCBCD 5
JavaEnterpriseEditionFaq - TomcatFaq
Here you are using reference of the object you already created and used as a key to retrive value. But when you create new object its hashcode value is different than original one because you are not overriding hashcode and equals method so it will look in different location and search for object which is not there so it will return null as a value
Meghna Bhardwaj wrote:HI Bob,
I think you misunderstood me.... I did not mean objects you add to Map must override equals() and hashCode().
I am saying that the book mentions the KEY of the Map, i.e. Map<key, value>, the key object used MUST override
the methods. In my example code, Student1 is the Key in the Map.
I disagree that just because you add an object to Map it MUST override those methods...this is not correct.
SCJP 6 - SCJD - SCWCD 5 - SCBCD 5
JavaEnterpriseEditionFaq - TomcatFaq
But still the reference variable s1...why does it find it? I am losing sleep over this so please put me out of my misery!
Maybe you can refer me to some site where it is explained in more detail etc... anything that helps. thanks.
SCJP 5.0 - JavaRanch FAQ - Java Beginners FAQ - SCJP FAQ - SCJP Mock Tests - Tutorial - JavaSE7 - JavaEE6 -Generics FAQ - JLS - JVM Spec - Java FAQs - Smart Questions