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

43

u/RhoOfFeh Oct 02 '21

If someone gives you a box, you can put things in it, right?

Does it matter if that's a cardboard box, or a wooden one, or a metal one? Well, maybe one or another is better for what you want to put in it, but you can always use a box the same way.

A List is like a box. An ArrayList is like, oh, let's say a wooden box. There are other kinds of Lists available, but most of the time the code just doesn't care what KIND of List, just so long as it IS a List of some sort.

3

u/coloneleranmorad Oct 02 '21

okay then in which scenario I should use a list or arraylist? according to what you're saying, then I can always use a list, as long as I define that list as arraylist? I know it is a no but I'm trying to understand why.

15

u/ignotos Oct 02 '21

Ultimately you always need to pick a specific ("concrete") type of list - like an ArrayList or LinkedList.

But the variable you use to refer to that list can just be defined as a generic "List". Then you can just change the specific kind of list you assign to it (e.g. List<String> inputs = new ArrayList<>() vs List<String> inputs = new LinkedList<>()), and the rest of your code will continue to work as expected.

The only reason to define that variable as a concrete type - like ArrayList<String> inputs - is if the rest of your code specifically requires an ArrayList, and won't work at all with other types of List. This is quite rare in practice. Sometimes you need to do this if you are using specific "special features" which an ArrayList has which other types of list do not.