Skip to main content

Posts

Showing posts from 2011

Understanding Equals and hashCode contract,and what can go wrong

SO what about Equals and hashcode?
Most people will say these are the two basic function available in Object class and could be called from any Class object created in Java. Well thats true but there is more then this.
First take a look at HashCode:
Every JVM provides a good hashCode implementation mostly based on the object's memory location and for two different object(by location) it produce different hashCode.
And at the same time Equal method also consider two different memory location object as Not Equal. So at core two are in a contract and works great.

But as soon as start writing code and write a class and create a state of a class(means create few data variables in a class), the core contract of hashCode and Equal doesnt work any more.
e.g.
Class MyFirstCLass{ int value; public MyFirstCLass(int value){ this.value = value; } } MyFistCLass obj1 = new MyFirstCLass(10); MyFistCLass obj2 = new MyFirstCLass(10);
Now obj1 and obj2, theoratically should be equal as both holds …

Difference between ArrayList and LinkedList

What is the difference between ArrayList and LinkedList

First of all lets see what Interfaces they implement.
ArrayList (See on Oracle/sun site)SerializableCloneableIterable<E>Collection<E>List<E>RandomAccessLinkedList(See on Oracle/Sun site)SerializableCloneableIterable<E>Collection<E>Deque<E>List<E>Queue<E>By looking at interface being implemented by these two collection, we could see RandomAccess is implemented by ArrayList and Queue<E>,Deque<E> implemented by LinkedList only. So all the differences between these two collections are because of these three Interfaces and their implementation.

RandomAccess : ArrayList can be accessed randomly, means we could access nth element of an ArrayList directly without affecting search/seek performance. e.g. list.get(n). Means get performance of nth element will never depend on how large is the ArrayList.It will remain constant.
While LinkedList cant be accessed randomly(though it does …