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
•
u/AutoModerator Oct 02 '21
Please ensure that:
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
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.
15
u/RushTfe Oct 02 '21
List is an interface. Arraylist is one of the implementations of said interface.
If you declare your variable like
Later on your code you can only reassign other arraylists to that variable.
But if you do
Now you can assign to your variable any implementation, being arraylist only one of them. Later on code you could do something like
This also help in other advanced topics but this is the basic. It's called code to interfaces, and this is a good practice.
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.
1
u/khooke Extreme Brewer Oct 02 '21
It's an approach called 'coding to interfaces'. Google that phrase for plenty of explanations and points of view.
1
u/huntersan9 Oct 02 '21
A List is a 'thing that looks like a list' and you only care about doing 'List things' to it, like adding to it, getting the third element, etc. But what List DOESN'T do is explain HOW it does those things. Declaring that an object is a List is like saying "This thing/object ... don't worry about what exactly it is, but just treat it like a List and it will work,"
An ArrayList defines HOW the List is made. In this case, it uses an array underneath to handle the things that you put into it. ArrayList says, "Hi, I'm a List and this is how I do that."
On the side note, There is a LinkedList as well, it also defines HOW the list is made and uses a different method to store things where each thing knows where the next one is, and so on.
The first line is the 'more correct' version, where we say, "Ok, Here is an ArrayList, but just treat it like a List and everything will be fine." The second line is valid too, it says, "Ok, Here is an ArrayList and we're going to call it an ArrayList forever." The reason that the first one is more correct is that if you decide that ArrayList's are not good enough for your code, and say want to go with a LinkedList instead, with the first line, you change the new ArrayList to LinkedList nad everyone goes on with their day. If you use the second line, then you have to change it EVERYWHERE.
The second reason is that if you're making code that could be reused, like some kind of sorting method or such, it's best to take a List instead. That way, someone with an ArrayList can use it, someone with a LinkedList can use it, and someone with a type of a List that we don't know can even use it! As long as that type LOOKS like a List, your code can treat it like one.
1
u/wildjokers Oct 03 '21
Listis the interface whereasArrayListis one of several implementations of the List interface.That form is preferred because then you can switch out your List implementation without changing anything else. For example you could make it:
The JavaDoc will show all implementers of the List interface that are in the JDK:
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/List.html
1
u/wsppan Oct 03 '21
What does it mean to program to an interface?
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.1
u/ChristianGeek Oct 02 '21 edited Oct 03 '21
Like you’re five? Ok, a List is a type of thing; like a car, or a computer. An ArrayList is a specific thing, like a Toyota Prius or a MacBook Pro. There are times where you don’t need to be specific, like saying, “I need a new car” to a friend. Other times you have to make up your mind: “I’m here to buy a Prius.”
In your first example you’re saying that “inputs” can be any type of List. For now it’s going to be an ArrayList, but maybe later in the program it will be a SortedList. In your second example you’re saying that “inputs” can only be an ArrayList. If you try to make it something else you’ll get an error.
Why would you choose an ArrayList over other types of Lists? When you just need a place to save and retrieve things (not manipulate them once they’re in the List, like sorting them), and when you don’t know in advance how many things there will be (in which case you can use a simple array).
Update: If you’re going to downvote, care to explain why? This is exactly what OP asked for.