Posty

Wyświetlanie postów z listopad, 2019

HashMap - how it works?

Obraz
With maps we can access stored objects (values) using keys assigned to them. One of Map interface implementation is HashMap   class. In this article we will have a look how  HashMap  can be used and how it works under the hood.  Basic Usage Lets have a look at basic usage of HashMap : We have used HashMap  to be able to quickly map a person's name to his car. It is a typical use case of a map.  As you can see Car class overrides two methods from Object class -  hashCode()  and  equals() . Those will be used by  HashMap   internally, as described in next section. It is important to remember two things: hashCode()  is used to assign a number to an object.  There is a contract between   hashCode() and equals() which must be fulfilled - when equals() returnes true for compared objects, then hashCode() values must be the same for both objects. To learn more about  hashCode()  have a look at the artcile -  hashCode() - how it works? How it works under the

hashCode() - how to implement it? Where is it used?

Method  hashCode() is inherited from Object class . Its purpose is to return an    int  value, which can be used to represent given object . There is a contract between   hashCode()   and  equals()  which says that whenever  equals()   method used to compare two objects return s true, then values returned by  hashCode()  functions called on those objects must be the same . Remember that it does not work like that vice versa -  when  hashCode() values are the same , then it does not mean that  equals()  invoked for those two objects will always return true.  hashCode()  method is widely used by java containers like HashMap and HashSet . That is why it is desired that  hashCode()  will return unique values for unique objects as often as it is possible since it can improve performace of these containers (however it is not concidered as an error when  hashCode()  returns the same value for different objects). How to implement it? Whenever you override an  equals() method, you will