Hashmap Java
Hashmap Java
=====================================================
-Hashmap is class which extends the AbstractMap and abstractmap implemennts the
map.
-Hashmap implements the map.
-Hashmap stores the data in the form of key and value pair.
where your key is unique.
-So here one object is used as key and another object used as value.
-If you try to insert duplicate key , it will replace the present element by
current one.
-It will not maintain insertion order.
example ->
Map<String, Integer> empMap = new HashMap<>();
empMap.put("EP5050", 21000);
empMap.put("EP5053", 45000);
empMap.put("EP5059", 1000);
empMap.put("EP5051", 89000);
empMap.put("EP5050", 32000);
empMap.put("EP5059", 8000);
empMap.remove("EP5050");
System.out.println("==============After remove operation============");
System.out.println("=====================================");
System.out.println(empMap.get("EP5059"));
System.out.println("=====================================");
System.out.println(empMap.containsKey("EP5059"));
System.out.println(empMap.containsValue(56000));
}
syntax:-
HashMap<K, V> hmap = new HashMap<>();
=========================================================
Internal Working of Hashmap.....
--------------------------------------------------------
- now when you called put() method of hashmap class, hashcod will be generated by
put method.
- after calling of hashcode() method, hashcode of inserted key is generated and
after that index is calculated to put the
inseted record in that array index
index = hashcode(key) & (length-1)
ex -->
hashcode() method
equals() method
hashcode() method-
- it is used to get hashcode of an object.
-it return the memory reference of an object in the form of integer.
- it calculate the bucket i.e. it calcualte the index.
equals() method -
=======================================
Hash collision --
hash collision is a situation where two or more distinct records can create same
hashcode that is same has bucket position in hahtable.
Ans ->
A contract is:
If two objects are equal then they should have the same hashcode
and if two objects are not equal then they may or may not have same hash code.
==============================================================================
For interview questions
https://www.interviewbit.com/hashmap-interview-questions/
================================================================
public Book() {
@Override
public int hashCode() {
return Objects.hash(bookName, id);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Book other = (Book) obj;
return Objects.equals(bookName, other.bookName) && id == other.id;
}
}
---------------------------------------------------
}
}