Java Programming - Objects and Collections
- Objects and Collections - General Questions
- Objects and Collections - Finding the output
- Objects and Collections - Pointing out the correct statements
class Test1
{
public int value;
public int hashCode() { return 42; }
}
class Test2
{
public int value;
public int hashcode() { return (int)(value^5); }
}
which statement is true?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.
Option B is wrong. The set can be modified.
Option D is wrong. This is a Set and not a Map.
- The value returned by hashcode() is used in some collection classes to help locate objects.
- The hashcode() method is required to return a positive int value.
- The hashcode() method in the String class is the one inherited from Object.
- Two new empty String objects will produce identical hashcodes.
(2) is an incorrect statement because there is no such requirement.
(3) is an incorrect statement and therefore a correct answer because the hashcode for a string is computed from the characters in the string.
- hashCode() doesn't have to be overridden if equals() is.
- equals() doesn't have to be overridden if hashCode() is.
- hashCode() can always return the same value, regardless of the object that invoked it.
- equals() can be true even if it's comparing different objects.
(3) and (4) are correct.
(1) and (2) are incorrect because by contract hashCode() and equals() can't be overridden unless both are 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.