5. (5 points) A hashCode function is used to compute a 32-bit integer representi
ID: 3919939 • Letter: 5
Question
5. (5 points) A hashCode function is used to compute a 32-bit integer representing an Object. Is the following hashCode function poorly written? yes or no and why. COverride public int hashCodeO int temp = 17; //returns a random integer return temp (new Random)).nextIntO 6. (5 points) An equals function is used to compare two objects for equality. Is the following hashCode function poorly written? yes or no and why. 0Override public boolean equals(Object o) if (thiso) return true; return this.xo.x kk this . y o.y && this.angle o.angle k this.currentHealtho.currentHealth;Explanation / Answer
The hashCode() method written above is incorrect.
because if two objects are equa as per equals method, then their hashCode must be same.
since ur hasCode is using random integer to generate hash code. it will be different for same object, because of random integer. if we want to know hash code as per ur implementation, it will be different at different times.
hash code and equals method have contract that if two objects are equal their hash codes must be same. which is not in ur case.
while as if two objects are different their hash codes may or may not be same.
ur equals() method is fine as it checks for each attribute to know whether one object is equal to another object or not. if two objects have same set of attributes having same values then it will return true.
so second method is fine as per implementation.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.