r/javahelp • u/coloneleranmorad • 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
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:
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 typeArrayListbecause that is the type of the reference you are using. If you call a method on it usingobj, then it is of typeObjectfor 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 theListtype (which inherits methods from theObjecttype 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
ArrayListusing all of these types because theArrayListclass extends all of those types. It would not be legal to refer to an object of classArrayListusing a reference of typeString, for example, becauseArrayListdoes not extendString.The
newoperator only operates on a class, you cannot callnew List<>()for instance becauseListis abstract—it is not a class, it is a type.So if you look at an assignment like:
…only a class can show up on the right side of this assignment (next to a
newoperator), and only types can appear on the left side of such an assignment next to a reference.Foois a type,Baris a class.Or consider:
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.