Category: HashMap

  • What will happen if you store null key in HashMap?

    What will happen if you store null key in HashMap?

    In HashMap, only one null key is allowed. If key of the HashMap is null then it will always be present in the index 0. NullPointerException is thrown if you try to call hashCode() method on null key.As a result, when a get() method is called then value of the first index is returned.

    Read article →

  • Can we use any class as a Map key in HashMap?

    Can we use any class as a Map key in HashMap?

    Yes. We can use any class as a Map key, however the following points should be considered before using them. If a class overrides an equals() method, it should also overrides hashCode() method. Best practice for user defined key class is to make immutable, so that the hashcode value can be cached for fast performance.

    Read article →

  • What is the importance of hashcode() and equals() methods?

    What is the importance of hashcode() and equals() methods?

    HashMap uses the key object hashCode() and equals methods to determine the index to put the key-value pair. The methods are also used when we try to get the value from HashMap. If these methods are not implemented correctly, two different keys might produce the same hasCode() and equals() output and in that case, rather

    Read article →