About Question com.enthuware.ets.scjp.v6.2.711 :

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
ETS User

About Question com.enthuware.ets.scjp.v6.2.711 :

Post by ETS User »

This is the question that uses the "info" class and questions about the use of the hashCode() and equals() methods.

The explanation for option C states:
In this particular case, since the keys (i.e. the two Info objects) are unequal as per their equals() method and even though their hashcode are same, the HashMap will work properly for them. Both the objects will be stored and retrieved. However, the retrieval will fail only for Info objects that break the rule of equals() and hashCode() are put in the map.
I added some code into the main method as follows:

Code: Select all

System.out.println("nbr of entries in map = " + map.size());
System.out.println("hashcode for i1 = " + map.get(i1).hashCode());
System.out.println("hashcode for i2 = " + map.get(i2).hashCode());
...and running the code returned this:
nbr of entries in map = 2
hashcode for i1 = 99162322
hashcode for i2 = 113318802
Perhaps I am misunderstanding this, but I see these statements saying the hashcodes are not the same.

Also, can you please clarify the final statement in the explanation box for this question that states:
In this case, equals() will return true for: new Info("aa", "b", "c") and new Info("a", "ab", "c") but their hashCode() values will be different.
I can certainly see how the hasCode() values will be different but how will the equals() method return true when adding either of these objects?

Thank you
Gary

JDSunny46

Re: About Question com.enthuware.ets.scjp.v6.2.711 :

Post by JDSunny46 »

ETS User wrote:can you please clarify the final statement in the explanation box for this question that states:
In this case, equals() will return true for: new Info("aa", "b", "c") and new Info("a", "ab", "c") but their hashCode() values will be different.
I can certainly see how the hasCode() values will be different but how will the equals() method return true when adding either of these objects?
It's the way the class was programmed to determine if the object is "functionally equivalent"....

Code: Select all

	public boolean equals(Object obj)
	{
		if(! (obj instanceof Info) ) return false;
		Info i = (Info) obj;
		return (s1+s2+s3).equals(i.s1+i.s2+i.s3);
	}
(this.s1,s2,s3) --> "aa" + "b" + "c" == "aabc"
(i.s1,s2,s3) --> "a" + "ab" + "c" == "aabc"

use hashcodes (or == ) to find out if it's the same location in memory.
use .equals() to find out if it's functionally equivalent (based on the overridden equals method in the class).

Post Reply

Who is online

Users browsing this forum: Google [Bot] and 41 guests