I am having a doubt regarding ArrayList and List. In which case we should use ArraryList like:
ArrayList obj = new ArrayList();
And in which case we should use List Interface.
List obj = new ArrayList();
What is the difference between them?
I am having a doubt regarding ArrayList and List. In which case we should use ArraryList like:
ArrayList obj = new ArrayList();
And in which case we should use List Interface.
List obj = new ArrayList();
What is the difference between them?
If you need to call a method that is specific to an implementation, use the implementation.
When you write :
List obj = new ... //ArrayList() or LinkedList()
the compiler only knows that obj is a List
. Hence, you cannot use methods that are specific to one implementation.
For example, if you need to access the last element of a LinkedList
, you need to declare it like this :
LinkedList = obj = new LinkedList();
Now, obj
is a LinkedList
. Hence, you can use obj.last()
.
If you want to use methods specific to ArrayList you want to first case, otherwise it's better to use the second case. With the second case you don't have to change as much if you want to switch to a different List implementation.