r/javahelp • • Oct 02 '21

Can someone please explain the difference between List and ArrayList like I'm five?

What exactly is the difference between

List<String> inputs = new ArrayList<>()

and

ArrayList<String> inputs = new ArrayList<>()

I've read some stuff about it but I'm a bit confused and I don't feel like I understood completely. Can someone explain the difference with some examples? Thank you!

30 Upvotes

29 comments sorted by

View all comments

15

u/RushTfe Oct 02 '21

List is an interface. Arraylist is one of the implementations of said interface.

If you declare your variable like

ArrayList<> myVar = new Arraylist<>();

Later on your code you can only reassign other arraylists to that variable.

But if you do

List<> myVar = new Arraylist<>();

Now you can assign to your variable any implementation, being arraylist only one of them. Later on code you could do something like

myVar = new Linkedlist<>();

This also help in other advanced topics but this is the basic. It's called code to interfaces, and this is a good practice.

3

u/[deleted] Oct 02 '21

why is code to interfaces good practice

3

u/knoam Oct 02 '21

Coding to interfaces is more flexible. Coding directly to classes means you have to keep using that class going forward. If you code to an interface, you can change out the class with another one later on.