Java Reference
In-Depth Information
The following DogTest program creates three Dog objects and test them for equality.
Examine the code and try to determine its output:
1. public class DogTest {
2. public static void main(String [] args) {
3. Dog one = new Dog(“Fido”, 3);
4. Dog two = new Dog(“Fido”, 3);
5. Dog three = new Dog(“Lassie”, 3);
6.
7. if(one.equals(two)) {
8. System.out.println(“Fido”);
9. }
10.
11. if(one.equals(three)) {
12. System.out.println(“Lassie”);
13. }
14.
15. if(one == two) {
16. System.out.println(“one == two”);
17. }
18. }
19. }
Because the Dog objects referred to by one and two have the same name and age ,
one.equals(two) is true and “Fido” is displayed. The “Lassie” object has a different
name, so one.equals(three) is false . The test for one == two is false because one and
two point to different (but equal) objects.
The hashCode Method
The Object class contains a method named hashCode with the following signature:
public int hashCode()
This method is used by hash table data structures. The hashCode and equals methods
are related in the sense that two objects that are equal should generate the same hash
Search WWH ::




Custom Search