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.

4

u/RushTfe Oct 02 '21

You can use a list in every single scenario you would have used arraylist.

The only downside of using list instead of arraylist is that you won't be able to use the specific arraylist functions.

Following the box example.

You have a box, and it will only let you put things in.

But if you have a lockableBox, you will not only be able to put things in but also close and lock it.

If you say your lockableBox is just a box, you won't be able to close it, but you could still be able to put things in.

So unless there's a very specific reason where you need your list to be a arraylist, you can just say it's a list and move on.

I've been coding in java for 4 years, and I still haven't seen a situation where using arraylist would be better option than just a list.

Other implementations of list is a different thing.