"No one is as deaf as the man who will not listen."
- (Proverb)
1.
class Test1
{
public int value;
public int hashCode() { return 42; }
}
class Test2
{
public int value;
public int hashcode() { return (int)(value^5); }
}
The so-called "hashing algorithm" implemented by class Test1 will always return the same value, 42, which is legal but which will place all of the hash table entries into a single bucket, the most inefficient setup possible.
Option A and D are incorrect because these classes are legal.
Option B is incorrect based on the logic described above.
Option C is correct. HashSet implements the Set interface and the Set interface specifies collection that contains no duplicate elements.
Option A is wrong. HashSet makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.
Which two statements are true about comparing two instances of the same class, given that the equals() and hashCode() methods have been properly overridden?
If the equals() method returns true, the hashCode() comparison == must return true.
If the equals() method returns false, the hashCode() comparison != must return true.
If the hashCode() comparison == returns true, the equals() method must return true.
If the hashCode() comparison == returns true, the equals() method might return true.
(1) is a restatement of the equals() and hashCode() contract. (4) is true because if the hashCode() comparison returns ==, the two objects might or might not be equal.
(2) and (3) are incorrect because the hashCode() method is very flexible in its return values, and often two dissimilar objects can return the same hash code value.