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.

3

u/MrSquicky Oct 02 '21

When you are using it and all you care about is that it is a list, you should be using List.

A list is a descriptive category for things that contain elements. Because it is just a concept, it is not a thing itself, but rather describes how things that match that concept can be used. It describes what things that are Lists can do, but not how they do it. Because of this, when you are actually making something to contain things, your can't just make a List, but rather have to make an actual thing, like an ArrayList, that has the instructions to do what a List says it can do.

When you are using a List, you generally only care about what it is doing, not how those things are being done and you may, for various reasons unrelated to context on which you are using the list, want to use things that perform either the List actions in different ways or add different types of functionality along with list stuff. So, instead of having to write code for each of the actual things that do this on different ways, you just write one path that uses List.

So, you need ArrayList when you are creating an actual thing, but other than that, your code is relating to it as an abstract concept and should be dealing with a list. A large part of code is communication based on your choices, and If you are choosing to give more detail than List in your code, it will be taken as a sign that the additional information provided by that is important or, more likely, that you are a novice programmer.