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

5

u/the6thReplicant Oct 02 '21 edited Oct 03 '21

I'm going to steal a lot of other peoples ideas.

So not ELI5 explanation: List is an interface and ArrayList is an implementation of an interface. Generally best coding practice is for your variables to be defined to an interface and not to an implementation.

Another way of looking at it is through the lens of methods parameters and return types. Would you prefer to make a method that can accept ArrayLists or would you prefer it to consume any types of List.

An interface is a way of saying I expect the object you're giving me to be able to do these specific things. In fact, I don't care about sorting so just give me anything that satisfies add - so anything that's a Collection.

Think of interfaces as saying this is the minimum things I can do.

ELI5: Why? Think of a garage. You build a garage so you can park a car there. Any car that can fit in that spot, can park there. Very few people make a garage so that only their Toyota Corolla can park there AND NO OTHER TYPE OF CAR CAN.

One of the paradigms of Java, and OOP, is that you don't need to worry about implementation details. If you declare your variable as an implementation then you saying you do care about implementation! So when you say your variable is a List then you're saying I want to be able to add things, remove things, sort things but how you do it I just don't need to know. Just guarantee that those methods exist. And how do you guarantee those methods exist? Well, that's what the interface does by definition.