r/learnjava • • Dec 02 '19

A question about List and ArrayList in Java

Is there a good reason why you would create a polymorphic type of ArrayList from List?

for example: List<String>someRandomList = new ArrayList<>();

Im trying to understand.

all comments are appreciated!

42 Upvotes

6 comments sorted by

25

u/anthropaedic Dec 02 '19

List is an interface, and ArrayList is an implementing class. It's almost always preferable to code against the interface and not the implementation. This way, if you need to change the implementation later, it won't break consumers who code against the interface

17

u/[deleted] Dec 02 '19 edited Dec 03 '19

thank you! I get IT! ArrayList IMPLEMENTS List! and I can replace ArrayList with any class that IMPLEMENTS List! Thank you again!

11

u/gonzohst93 Dec 03 '19

This is such an important concept, we learned abstract classes and interfaces in class but we didn't really cover why we use them. It took me a long time for it to click after seeing people create interfaces at work and then during a 3rd year course at university where we really covered this stuff

1

u/TheKingElessar Dec 03 '19

How would you describe them? I haven't taken a course on Java, but from what I've read they're mostly a safety measure so that you know the class does what it's supposed to.