1

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

1

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

Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
  • can you please tell me the same example in ArrayList scenario. when i write ArrayList obj = new ArrayList(); and List lst = new ArrayList(); In both cases i can get the same method. then what is the diff ? – Arvind Vishwakarma Apr 22 '14 at 12:27
  • @ArvindVishwakarma I don't know any method that is specific to the ArrayList. This implementation is only a list stored in an array. – Arnaud Denoyelle Apr 22 '14 at 12:30
0

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.

Harry Blargle
  • 416
  • 2
  • 11
  • 18