Multiple choice technology programming languages

Q: 1 Given: 11. public class Person { 12. private String name, comment; 13. private int age; 14. public Person(String n, int a, String c) { 15. name = n; age = a; comment = c; 16. } 17. public boolean equals(Object o) { 18. if (! (o instanceof Person)) return false; 19, Person p = (Person)o; 20. return age == p.age && name.equals(p.name); 21. } 22. } What is the appropriate definition of the hashCode method in class Person?

  1. A. return super.hashCode();

  2. B. return name.hashCode() + age * 7;

  3. C. return name.hashCode() + comment.hashCode() / 2;

  4. D. return name.hashCode() + comment.hashCode() / 2 - age * 3;

Reveal answer Fill a bubble to check yourself
B Correct answer
Explanation

A good hashCode implementation should combine significant fields using non-zero multipliers and handle null checks or existing field hashes appropriately. Option B combines the hash of the name string with the age field multiplied by a prime number, fulfilling standard contract requirements.