File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes whizlabs mock: final varables in equal and hashcode? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "whizlabs mock: final varables in equal and hashcode?" Watch "whizlabs mock: final varables in equal and hashcode?" New topic
Author

whizlabs mock: final varables in equal and hashcode?

adam Lui
Ranch Hand

Joined: Sep 03, 2007
Posts: 186
[code]
public class TestHash {
private int length;
private int width;
private final double area;

public TestHash (int l, int w)
{
length = l;
width = w;
area = length * width;
}
}
[code]

from this example, I learnt a final variable and a variable changeble by two variables should be involved in hashcode manipulation, what about for equals?

it makes sense for me to use it for equals, for example,
final integer for area, of shapes, can be used to compare so is one of the methods to find out if they are equal objects.
am i right?! :roll:
[ November 13, 2007: Message edited by: adam Lui ]
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Howdy Adam,

as long as the hash code contract is fulfilled, you can use the area variable for equals and for hashCode.

But this is more a question of what you want:
If a 3*7 and a 7*3 rectangle should be treated as equal, because the area is the same, you could use the area variable for equals and hashCode.
If you're looking at them as being not equal because the first looks like

and the second looks like


then you could use area in hashCode but not in equals.
Only the hashCodes must be the same if equals returns true.

The fact that it is final is not important here. By the way, the other variables are also kind of final, because there is no method to change them after they get their values (once and for all) in the constructor.

Hope I got your question right,
Bu.


all events occur in real time
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: whizlabs mock: final varables in equal and hashcode?