Posts

Showing posts with the label equals

Characteristics of Object.equals()

I am come across the characteristics specified for implementation of equals() method in Java Classes. There is nothing like which we don’t know, but here it is well explained. I thought of sharing the same just for recalling old Java learning days Here are the characteristics that every implementation of Object.equals() should follow Reflexive. For any non-null reference value x, x.equals(x) should return true Symmetric. For any non-null reference values x and y. x.equals(y) should return true if and only if y.equals(x)   returns true. Transitive. For any non-null references value x,y and z , it x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true . Consistent. For any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified. For any non-null reference value x, x.equals(null) ...

Java puzzle–StringBuffer

What will be the output of following program ? 1: class StringBufferTest2 2: { 3: public static void main(String[] args) 4: { 5: StringBuffer sb1,sb2; 6: sb1 = new StringBuffer(); 7: sb2 = new StringBuffer(); 8: sb1.append(" Hello "); 9: sb1.append(" Hello "); 10: boolean result = sb1.equals(sb2); 11: System.out.println(" Result = "+ result); 12: } 13: }

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...