image

Cracking Core Java Interviews 3rd Edition

A Comprehensive Guide to Crack Core Java Interviews in Investment Banks, HealthCare IT & Startups. It covers Core Java, Algorithms, Data Structures, Concurrency, Hibernate and Spring MVC.

Specifically for investment banking domain, healthcare IT and product companies i.e. UBS, RBS, Blackrock, Morgan Stanley, JP Morgan, Nomura, Barclays, Citibank, Markit, Bank of America, Goldman Sachs and other companies i.e. Global Logic, Adobe, hCentive, Edifecs, Expedia, Infosys, TCS, Sapient, Wipro, HCL etc.
Free Chapters PDF
1006 downloads
Buy Full PDF ₹250
3rd Edition
Last Updated : Tuesday, February 2, 2016 1:04:40 PM IST Total Page Hits 584

How will you make a custom class object as Hashmap Key

There are two methods that a class needs to override to make objects of that class work as hash map keys.

public int hashCode();
public boolean equals(Object o);

But you must obey the contract between hashCode and equals method while overriding them in your new Class.

Contract for hashCode and equals method

  1. The equals() method must return true if the fields of the current object equal those of the object passed in, else return false. By “equal”, we generally mean that primitive fields match via the == operator, and objects are either both null or both non-null and match via the equals() method. Note two important constraints on equals():

  2. if x.equals(y) returns true, then the hash codes of x and y must be identical;

  3. it must be reflexive and transitive: that is, x.equals(y) must return the same value as y.equals(x), and if x.equals(y) and y.equals(z), then x.equals(z) must also be true (see below for what this actually means in real terms!).
If you do not obey the Contract Rules between hashCode and equals method then unpredictable results can happen, for example you may not be able to get newly inserted item back from hashmap or in worst case a wrong object could be returned for the given key.



Similar Articles

1. Synechron Java Interview Questions

Collection of Java Interview Questions (Core Java, Spring, database and other concepts) for Synechron in banking and finance domain

2. Design Metro Smart Card System for Delhi using Java

Design a program in Java for Metro Smart Card System in Delhi. Evaluation criteria will be based on code completeness, code structure and quality, modularity, usage of OO principles, choice of data structure and unit tests.

3. What does volatile keyword do in a multi-threading environment

volatile keyword helps programmers write thread safe program