This is a practice exercise from a book by Koffman. Data Structures: Abstraction and Design Using Java, 3rd Edition.
I have a series of questions. I have had 2 attempts at the equals method. Lines 21-29 are what made sense to me logically without checking references, and 32-41 are adapted from the book.
Are lines 20-30 a correct implementation of an equals() override method? Can I have 2 String parameters and check if these parameters match with the Person Objects 2 String parameters?
Lines 33-41 I have no idea what is occurring or if it's correct. I stole the code from the book but changed implementation here for 2 String parameters?
2 a) Are these lines correct to start with?
2 b) What does instanceof on line 34 check for exactly here? Just that Person is an Object too? Or more?
2 b 1) If there's more to 2a, what else is being checked?
3 ) Line 45 and 46, What is this method actually doing?
1 public class Person { 2 3 String lastName; 4 String firstName; 5 6 7 public Person(String lastName, String firstName) { 8 this.lastName = lastName; 9 this.firstName = firstName; 10 } 11 12 public String toString() { 13 14 String result = ("First name: " + firstName + 15 "\nLast name: " + lastName); 16 17 return result; 18 } 19 20 public boolean equals(String lastName, String firstName) { 21 22 if (this.lastName == lastName && this.firstName == firstName) { 23 24 25 return true; 26 } 27 28 return false; 29 30 } 31 32 33 public boolean equals(Object obj) { 34 if (obj instanceof Person) { 35 return firstName.equals(((Person) obj).firstName) 36 && lastName.equals(((Person) obj).lastName); 37 38 } 39 40 return false; 41 } 42 43 44 45 public int hashcode() { 46 return lastName.hashCode() + firstName.hashCode(); 47 } 48 49 50 51 52 }