Search code examples
javascjp

logic from SCJP book related to Collections


public class Person {

    private String name;

    public Person(String name) {
        this.name = name;
    }
    public int hashCode() {
        return 420;
    }
}

Based on the above program the answer is:

Answer: The time to find the value from HashMap with a Person key depends on the size of the map.

I have no clue/idea how come the answer is as above. I thought it was wrong hashcode() method implementation but the only options are as follows:

  • Which statement is true?
  • A. The time to find the value from HashMap with a Person key depends on the size of the map.
  • B. Deleting a Person key from a HashMap will delete all map entries for all keys of type Person.
  • C. Inserting a second Person object into a HashSet will cause the first Person object to be removed as a duplicate.
  • D. The time to determine whether a Person object is contained in a HashSet is constant and does NOT depend on the size of the map.

Answer: A

If anybody can provide some understanding on the same will be great as I won't be able to find any answers on the net for this


Solution

  • HashMap uses hashcode to place the entries in the bucket and equals to locate them. If all entries have the same hashcode then they will all end up in the same bucket. Now whenever you will request something from the map , the hashmap will go through all the entries from the same bucket and call equals on each entry to find the one requested by you. That's why

    The time to find the value from HashMap with a Person key depends on the size of the map.

    is correct answer