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

2

u/RushTfe Oct 02 '21
  1. Later you will use spring to inject dependencies, this way you can have many implementations for a single interface and inject the one you need. If you instance the implementation directly you wouldn't be able to use it.

  2. You can also create methods and accept the interface as parameter, so this method can apply to every implementation.

  3. Helps to have a cleaner code.

  4. Helps to develop tests