-
hashCode method execution
Dear Members :
I have custom hashCode method in conjunction with overriden equals method, in my program and have following doubts/observations :
[1] In order to verify whether the hashCode method is executed, I put a println statement within method, but this doesn't output when the program is run.
[2] The program is a simple equality testing of two dates and doesn't make use of any map. I want to know when and who gives (implicit ?) call to this hashCode method, when equals method is overriden, I mean the program flow.
Since SUN suggests to override hashCode, whenever equals method is overriden, and my program is not making use of map, how and when the hashCode method gets called and if so why my test print is not executed ?
Thanks in advance.
Atanu
-
Welcome to DevX 
It would help immeasureably if you posted the code you are running.
I don't answer coding questions via PM or Email. Please post a thread in the appropriate forum section.
Please use [Code]your code goes in here[/Code] tags when posting code.
Before posting your question, did you look here?
Got a question on Linux? Visit our Linux sister site.
Modifications Required For VB6 Apps To Work On Vista
-
hashCode method execution
Hi Hack :
The following is taken from Sun's SL-275 training material, with the added println stmt in hashCode method, to see if and when it is executed (implicitly?).
Code:
class MyDate {
private int day;
private int month;
private int year;
/**
* Constructor
* ===========
**/
public MyDate(int d, int m, int y) {
day = d; month = m; year = y;
}
/**
* Overriding equals method
* ========================
**/
public boolean equals(Object o) {
boolean result = false;
if (o != null && (o instanceof MyDate)) {
MyDate d = (MyDate) o;
if ( (day == d.day) && (month == d.month) && (year == d.year) ) {
result = true;
}
}
return result;
} // equals()
/**
* Overriding hashcode method
* ==========================
**/
public int hashCode() {
System.out.println("Overriden hashCode");
return (day^month^year);
}
} // MyDate class
public class TestDateEquals {
public static void main(String[] args) {
MyDate date1 = new MyDate(21, 8, 2008);
MyDate date2 = new MyDate(21, 8, 2008);
if (date1 == date2) {
System.out.println("date1 is identical to date2");
} else {
System.out.println("date1 is not identical to date2");
}
if (date1.equals(date2)) {
System.out.println("date1 is equal to date2");
} else {
System.out.println("date1 is not equal to date2");
}
} // main()
} // TestDateEquals class
-
Why do you think that the hash method is called when the equals method is called? Your code says its not. Here's a slightly modified version:
Code:
class MyDate {
private int day;
private int month;
private int year;
/**
* Constructor
* ===========
**/
public MyDate(int d, int m, int y) {
day = d; month = m; year = y;
}
/**
* Overriding equals method
* ========================
**/
public boolean equals(Object o) {
System.out.println("equals with " + o);
boolean result = false;
if (o != null && (o instanceof MyDate)) {
MyDate d = (MyDate) o;
if ( (day == d.day) && (month == d.month) && (year == d.year) ) {
result = true;
}
}
return result;
} // equals()
/**
* Overriding hashcode method
* ==========================
**/
public int hashCode() {
System.out.println("Overriden hashCode");
try{throw new Exception("Who called");}catch(Exception x) {x.printStackTrace();}
return (day^month^year);
}
} // MyDate class
public class TestDateEquals {
public static void main(String[] args) {
MyDate date1 = new MyDate(21, 8, 2008);
MyDate date2 = new MyDate(21, 8, 2008);
if (date1 == date2) {
System.out.println("date1 is identical to date2");
} else {
System.out.println("date1 is not identical to date2");
}
if (date1.equals(date2)) {
System.out.println("date1 is equal to date2");
} else {
System.out.println("date1 is not equal to date2");
}
} // main()
} // TestDateEquals class
/* Output from above:
Running: "C:\Program Files\Java\j2re1.4.2_08\bin\java.exe" -cp D:\JavaDevelopment\Testing\ForumQuestions2\;D:\JavaDevelopment;. TestDateEquals
date1 is not identical to date2
Overriden hashCode
java.lang.Exception: Who called
at MyDate.hashCode(TestDateEquals.java:62)
at java.lang.Object.toString(Unknown Source)
at java.lang.String.valueOf(Unknown Source)
at java.lang.StringBuffer.append(Unknown Source)
at MyDate.equals(TestDateEquals.java:42)
at TestDateEquals.main(TestDateEquals.java:83)
equals with MyDate@7c5
date1 is equal to date2
0 error(s)
*/
Last edited by Norm; 08-21-2008 at 08:57 PM.
-
hashCode method execution
Hi Norm :
Thanks immense for the code change and getting the hashCode method executed. Now -
[1] As suggested by SUN, if I do override hashCode along with equals, but do not make such explicit call ( as you did from equals) then hashCode method won't be executed, so what's the whole purpose of doing this ?
[2] I understand this much, that had my program involved maps, then hashCode would be invoked automatically while inserting, containing the itmes. I mean, in that case it makes sense to override hashCode, otherwise in such a simple programs (the code which you changed), why should I do this as per Sun's recommendation - am I right ?
If you could please clear this confusion - will be great.
Thanks again.
Atanu
-
Sorry, I haven't seen Sun's recommendation. Could you tell me where I could see it?
-
I looked fairly extensively and I couldn't find the SL-275 training material on line. It appears to be something you get, or get access to, once you have gone through their training.
I don't answer coding questions via PM or Email. Please post a thread in the appropriate forum section.
Please use [Code]your code goes in here[/Code] tags when posting code.
Before posting your question, did you look here?
Got a question on Linux? Visit our Linux sister site.
Modifications Required For VB6 Apps To Work On Vista
-
hashCode method execution
Hi Norm & Hack :
Thanks very much.
Yes you are correct, by virtue of undergoing SCJP training the study material named SL-275 from SUN, is the source.
Norm - their recommendation is in this book only and you can believe me, kind of strage, the way they blindly recommneded, w/o proper justifications.
Thanks again and have nice time.
Atanu
-
 Originally Posted by Atanu_Banerjee
Thanks again and have nice time.
Does this mean that your question has been answered and you consider this issue resolved?
I don't answer coding questions via PM or Email. Please post a thread in the appropriate forum section.
Please use [Code]your code goes in here[/Code] tags when posting code.
Before posting your question, did you look here?
Got a question on Linux? Visit our Linux sister site.
Modifications Required For VB6 Apps To Work On Vista
-
hashCode method invocation
Hi Hack :
Well almost - will be complete, if Norm replies about my last quey to him, which is - if I do not put that (extra) statement in equals method, as he did, is there any other way (implicitly), getting the hashCode method invoked. And this is a situation where there is no usage of map.
So my original quey is answered partially.
Thanks
Atanu
-
I have no idea where hashCode is called other than for maps.
Excepting the call to the Object toString() method which calls it as shown in the code I posted above.
-
hashCode Method Execution
The requirement for overriding hashCode when you override equals is not because equals calls hashCode. In fact, you can override equals in many instances without overriding hashCode and you'll get away with it.
This requirement is a "correctness of object design" requirement. It is based on the expectations for Object.hashCode in the java.lang.Object specification. Since all objects derive from Object, correctly written java must fulfill those expectations.
For many simple programs, or programs where you control the entire object hierarchy, you can break these expectations and get away with it. However doing so will eventually cause bugs in your program that you won't expect. It also becomes a bigger issue when others use your objects.
Joshua Block explains it here best in Effective Java, Item 8. You can read it here:http://books.google.com/books?id=ZZO...esult#PPA36,M1
Briefly, it's a good design principle and you should follow it.
Hope this helps,
alan
Similar Threads
-
Replies: 1
Last Post: 06-13-2008, 08:11 AM
-
Replies: 1
Last Post: 04-21-2006, 11:51 AM
-
Replies: 1
Last Post: 04-13-2006, 04:57 AM
-
By Alan Shiers in forum Java
Replies: 0
Last Post: 03-15-2002, 12:51 PM
-
Replies: 3
Last Post: 04-13-2001, 09:13 PM
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks