Posts

Showing posts with the label 5

HashMap hashCode collision by example

Image
As we all know Hash is a part of Java Collection framework and stores key-value pairs. HashMap uses hash Code value of key object to locate their possible in under line collection data structure, to be specific it is nothing but array. Hash code value of key object decide index of array where value object get stored. As per hashcode – equals method implementation rules Objects that are equal according to the equals method must return the same hashCode value. & If two objects are not equal according to equals, they are not required to return different hashCode values. As per above statement it is possible that two different object may have same hashcode values, this is called hashcode collision . To overcome this problem concept of bucket has been introduced. All the Value objects whose corresponding Key’s hashcode values are same , they fall under same bucket. Above diagram explains hash code collision. There are three key-value entries are shown , out of which second and thi...

How to avoid NPE while Auto-Unboxing

Auto-Boxing/Unboxing is introduced in Java 5 version. It supports automatic conversion of primitive type (int, boolean, float, double) to their equivalent Objects ( Integer, Boolean, Float, Double) in assignment , method and constructor invocation and other way also. Here is the examples Auto-Boxing Integer i = 10; // Auto-boxing converts primitive int value to Integer Object Auto-Unboxing int i = 0; i= new Integre(10); // Auto-Unboxing converts Integer Object to primitive int There is serious problem with using Auto-bocing/Unboxing, it may result null pointer exception. Take an example of following program package testproject; public class TestAutoUnboxing { private static TestAutoUnboxing test= new TestAutoUnboxing(); //cause Null Pointer Exception public static final Boolean YES = true; // Autoboxing for private boolean amIHappy = YES; // Instance Variable public static void main(String[] args){ System.o...