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!
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.
3
u/coloneleranmorad Oct 02 '21
okay then in which scenario I should use a list or arraylist? according to what you're saying, then I can always use a list, as long as I define that list as arraylist? I know it is a no but I'm trying to understand why.
15
u/ignotos Oct 02 '21
Ultimately you always need to pick a specific ("concrete") type of list - like an ArrayList or LinkedList.
But the variable you use to refer to that list can just be defined as a generic "List". Then you can just change the specific kind of list you assign to it (e.g.
List<String> inputs = new ArrayList<>()vsList<String> inputs = new LinkedList<>()), and the rest of your code will continue to work as expected.The only reason to define that variable as a concrete type - like
ArrayList<String> inputs- is if the rest of your code specifically requires an ArrayList, and won't work at all with other types of List. This is quite rare in practice. Sometimes you need to do this if you are using specific "special features" which an ArrayList has which other types of list do not.5
u/RhoOfFeh Oct 02 '21
The simple rule for me is this: Use the interface as everywhere as I can.
In other words, up until using List gives me a syntax error because there's no such thing as 'new List()', I'm not specifying a concrete type anywhere.
4
u/RushTfe Oct 02 '21
You can use a list in every single scenario you would have used arraylist.
The only downside of using list instead of arraylist is that you won't be able to use the specific arraylist functions.
Following the box example.
You have a box, and it will only let you put things in.
But if you have a lockableBox, you will not only be able to put things in but also close and lock it.
If you say your lockableBox is just a box, you won't be able to close it, but you could still be able to put things in.
So unless there's a very specific reason where you need your list to be a arraylist, you can just say it's a list and move on.
I've been coding in java for 4 years, and I still haven't seen a situation where using arraylist would be better option than just a list.
Other implementations of list is a different thing.
3
u/MrSquicky Oct 02 '21
When you are using it and all you care about is that it is a list, you should be using List.
A list is a descriptive category for things that contain elements. Because it is just a concept, it is not a thing itself, but rather describes how things that match that concept can be used. It describes what things that are Lists can do, but not how they do it. Because of this, when you are actually making something to contain things, your can't just make a List, but rather have to make an actual thing, like an ArrayList, that has the instructions to do what a List says it can do.
When you are using a List, you generally only care about what it is doing, not how those things are being done and you may, for various reasons unrelated to context on which you are using the list, want to use things that perform either the List actions in different ways or add different types of functionality along with list stuff. So, instead of having to write code for each of the actual things that do this on different ways, you just write one path that uses List.
So, you need ArrayList when you are creating an actual thing, but other than that, your code is relating to it as an abstract concept and should be dealing with a list. A large part of code is communication based on your choices, and If you are choosing to give more detail than List in your code, it will be taken as a sign that the additional information provided by that is important or, more likely, that you are a novice programmer.
2
u/morhp Professional Developer Oct 02 '21
Unless you need a specific list type for some reason (you probably don't) always use
List<...>for the variable type.If you want to create a new list
new ArrayList<>()on the right ride is usually the right approach if you need a list that you can change later, but you can create lists in many other ways, likenew LinkedList<>()orArrays.asList()orList.of(...)orList.copyOf(...).You can't write
new List<>()directly, as Java wouldn't know what type of List to create (like if you want a wooden or metal box), if you use methods likeList.copyOf()Java will decide that for you and automatically choose a good implementation for the amount of items and so on from inside the method.2
u/Bodine12 Oct 02 '21 edited Oct 02 '21
You will never use a List, because it’s an interface. You must use an implementation of a list, like ArrayList or LinkedList. Each one has different ways of implementing the common interface methods. So if you decide to change from arraylist to linkedlist it’s no problem because the different implementation will be called. However, if you explicitly declare ArrayList = New ArrayList you can no longer do that because the variable is bound to the concrete type ArrayList. Edited to add: The cases where you would want to limit yourself to a concrete type would be when the concrete type has methods that aren’t on the List interface. LinkedList especially. If you would declare “List myList = new LinkedList” then you will only have List interface methods available to you. If instead you declare “LinkedList mylist = new LinkedList()” then you’ll have all the LinkedList methods, but then the trade off is that variable couldn’t be switched to an ArrayList because ArrayList doesn’t have those extra methods.
1
u/denisfalqueto Oct 03 '21
You should get familiar to "coding to interfaces", that's the general technique. An introductory article is this one; https://www.infoworld.com/article/2076468/smarter-java-development.html
6
u/cervantesrvd Oct 02 '21
That's the easiest and best explanation/comparison I've seen. Will tell that to my newbie friend. Kudos and thanks mate!
1
2
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
ArrayList<> myVar = new Arraylist<>();Later on your code you can only reassign other arraylists to that variable.
But if you do
List<> myVar = new Arraylist<>();Now you can assign to your variable any implementation, being arraylist only one of them. Later on code you could do something like
myVar = new Linkedlist<>();This also help in other advanced topics but this is the basic. It's called code to interfaces, and this is a good practice.
3
Oct 02 '21
why is code to interfaces good practice
5
u/ignotos Oct 02 '21 edited Oct 02 '21
Essentially if it doesn't matter which specific kind of list you use in your code, then it's unnecessarily rigid and restrictive to write your code to only work with a specific kind of list.
If you later wanted to switch it out for a different kind of list (maybe because you did some tests and realised LinkedList would be more efficient, for example), then that will be easier to do if you referred to List as opposed to ArrayList throughout all of your code.
This generally makes your code more flexible and reusable. It also makes it easier to test - let's imagine you wanted to plug in a special kind of list which records and writes out a log all of the items which are added or removed, so you can analyse that information - if you used "List" throughout your code, you could pass in your SuperSpecialAnalyzingList and it would just immediately work. Whereas if you defined all of your variables as "ArrayList", you'd need to go through and change all of them.
3
u/knoam Oct 02 '21
Coding to interfaces is more flexible. Coding directly to classes means you have to keep using that class going forward. If you code to an interface, you can change out the class with another one later on.
4
u/RhoOfFeh Oct 02 '21
For now, trust us.
It's smart to learn from your own mistakes. It's smarter to learn from the mistakes of others. This path is now a limited access highway.
One of the the core reasons that it's a good practice is that it offers inversion-of-control via dependency injection, which allows us to separate core business logic from implementation specific details, and everything about how the system talks to the world, including its own internal data storage, is such a detail. If you were ready for that, great. If not, you will be one day.
1
Oct 02 '21
i dont know i seem to be running circles in java, dont really understand how to use java standard methods since im translating between english and native language
1
u/RhoOfFeh Oct 02 '21
That's why I started with 'trust us', although I didn't know about the language barrier, which speaks well of your writing.
The technical reasons for many design decisions are beyond easy understanding until one has a certain amount of experience. Even for a native speaker, that last paragraph was designed to be dense with very meaning-heavy words. I wouldn't expect most new programmers to understand it properly.
2
u/RushTfe Oct 02 '21
Later you will use spring to inject dependencies, this way you can have many implementations for a single interface and inject the one you need. If you instance the implementation directly you wouldn't be able to use it.
You can also create methods and accept the interface as parameter, so this method can apply to every implementation.
Helps to have a cleaner code.
Helps to develop tests
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
List is the interface whereasArrayList is one of several implementations of the List interface.
List<String> inputs = new ArrayList<>()That form is preferred because then you can switch out your List implementation without changing anything else. For example you could make it:
List<String> inputs = new LinkedList<>()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/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.
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.
•
u/AutoModerator Oct 02 '21
Please ensure that:
Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
You include any and all error messages in full
You ask clear questions
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.