Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why assign a new ArrayList to a List variable?

Tags:

java

I am new to java and when I go through the code of many examples on net I see people declaring the variable for an ArrayList as simply List in almost all the cases.

List<String> myList = new ArrayList<String>();

I don't understand if there is some specific advantage of doing this. Why can't it be an ArrayList itself, like so:

ArrayList<String> myList = new ArrayList<String>();
like image 664
Rasmus Avatar asked Jun 13 '12 02:06

Rasmus


1 Answers

It's called programming to an interface. It allows you to substitute that ArrayList for a LinkedList if somewhere down the line you decide that a LinkedList would be more appropriate.

like image 86
Jeffrey Avatar answered Oct 02 '22 00:10

Jeffrey