Java OCA OCP Practice Question 2327

Question

Given the following code.

class Book { 
    String isbn; 
    Book(String isbn) {this.isbn = isbn;} 
    public int hashCode() { 
        return 1234; 
    } 
} 

Select the correct option.

  • a Objects of the class Book can never be used as keys because the corresponding objects wouldn't be retrievable.
  • b Method hashCode() is inefficient.
  • c Class Book will not compile.
  • d Though objects of class Book are used as keys, they will throw an exception when the corresponding values are retrieved.


b

Note

Method hashCode() returns the same hash code for all the objects of this class.

This essentially makes all the values be stored in the same bucket if objects of the preceding classes are used as keys in class HashMap (or similar classes that use hashing), and reduces it to a linked list, drastically reducing its efficiency.

Option (a) in incorrect.

Book instances can be used to retrieve corresponding key values but only in limited cases-when you use the same keys (instances) to store and retrieve values.

Even though hashCode() will return the same value for different Book instances, equals() will always compare the reference variables and not their values, returning false.




PreviousNext

Related