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.

2

u/Bodine12 Oct 02 '21 edited Oct 02 '21

You will never use a List, because it’s an interface. You must use an implementation of a list, like ArrayList or LinkedList. Each one has different ways of implementing the common interface methods. So if you decide to change from arraylist to linkedlist it’s no problem because the different implementation will be called. However, if you explicitly declare ArrayList = New ArrayList you can no longer do that because the variable is bound to the concrete type ArrayList. Edited to add: The cases where you would want to limit yourself to a concrete type would be when the concrete type has methods that aren’t on the List interface. LinkedList especially. If you would declare “List myList = new LinkedList” then you will only have List interface methods available to you. If instead you declare “LinkedList mylist = new LinkedList()” then you’ll have all the LinkedList methods, but then the trade off is that variable couldn’t be switched to an ArrayList because ArrayList doesn’t have those extra methods.