﻿ Why is hashcode check not enough for strings comparison - Mar Java Mit Java

# Why is hashcode check not enough for strings comparison

We know when we have to see if two strings or objects are same or not, we first compare the hashcode values of each object. If hashcodes differ they are definitely not equal but if hashcodes are same we go for equals methods which compares the internal content.

But why is hashcode comparison not enough?

Answer is hash collisions. There are chances that two different objects might have same hashcode. Lets do some mathematics.

A hashcode is an integer, so it can have 2³² == 4294967296 possible values.
A char is a 16 bit value, so it can have 2^16 = 65536 combinations. A String is a sequence of characters which can have an int length, so a String can be as big as 2^31 =2147483648 characters. So any of these 65536 characters can occupy any of these 2147483648 length. So in practical we can have 65536²¹⁴⁷⁴⁸³⁶⁴⁸ combinations possible which is way less than the limit of hashcodes.

This is why hash collisions can happen and hashcode comparison primarily helps in checking if two objects are UNEQUAL or not Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)