List - ArrayList preserves order
List
is an interface, while the ArrayList
class is its most often used implementation. Both are residing in the java.util
package. The ArrayList
class has a few more methods - in addition to those declared in the List
interface. The removeRange()
method, for example, is not present in the List
interface but available in the ArrayList
API.
Prefer variable type List
It is a good practice, while creating an object of an ArrayList
, to assign its reference to a variable of type List
:
List listOfNames = new ArrayList();
More likely than not, using a variable of type ArrayList
will not change anything in your program, not today, nor in the future:
ArrayList listOfNames = new ArrayList();
The preceding reference can still be passed to any method that accepts a parameter of type List
. However, coding to an interface (that is what we do when we make the variable of an interface type) is a good habit in general because you never know when the requirements to your code might...