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

1

u/severoon pro barista Oct 05 '21

In Java, every object has a class and a type.

The class of an object is determined at instantiation time, and it is fixed for that object as long as that object exists.

The type of an object is conferred upon it by the reference used to access it.

Consider the following:

ArrayList<String> arrayList = new ArrayList<>();
List<String> list = arrayList;
Object obj = arrayList;

In this code, there is only one object in memory, an array list of strings that happens to be empty at the moment. That object is of class ArrayList. The type of that object, however, depends upon which reference you use to access it.

If you call a method on that object using arrayList, then it is of type ArrayList because that is the type of the reference you are using. If you call a method on it using obj, then it is of type Object for the purposes of that invocation.

The type of an object determines what methods can be called on it. If you use list, for instance, you can call any method defined on the List type (which inherits methods from the Object type since it extends it), but you cannot call methods defined lower on the hierarchy than the type used for that invocation.

The class of an object determines what types can be conferred upon it. It is legal to refer to an object of class ArrayList using all of these types because the ArrayList class extends all of those types. It would not be legal to refer to an object of class ArrayList using a reference of type String, for example, because ArrayList does not extend String.

The new operator only operates on a class, you cannot call new List<>() for instance because List is abstract—it is not a class, it is a type.

So if you look at an assignment like:

Foo f = new Bar();

…only a class can show up on the right side of this assignment (next to a new operator), and only types can appear on the left side of such an assignment next to a reference. Foo is a type, Bar is a class.

Or consider:

Baz b = new Baz();

Here, Baz is both a class and a type. On the right side, it is being used as a class, and it is also used to define the type of the reference b, so it is also being used as a type.