List & ArrayList in Java [duplicate] - java

This question already has answers here:
Type List vs type ArrayList in Java [duplicate]
(15 answers)
Closed 9 years ago.
Hi,I am a beginner of Java, I was taught to use "ArrayList" in OO programming in the Java lecture, however, I came across "List" today and have no idea how to use it, so what the difference between ArrayList and List? And what the same attributes of them?
something like:
List<...>list=new List<...>()
ArrayList<...>list=new ArrayList<...>()

List is an interface, whereas ArrayList is a concrete class that implements that interface

List is an interface.
ArrayList is a class that implements List.
You can't instantiate an interface, you have to instantiate one of classes which implements it.

List defines the basic contract that is expected that implementations would provide. ArrayList is a implementation of this contract that is backed by a dynamic array.
The great thing about this idea is, if you have a method that needs access to some kind of List, you can simply ask that callers pass you any implementation of List, meaning you don't need to know or care how the List is actually implemented, only that it will provide the contract described by List
You can't create an instance of List directly, you need to use one of the implementations, like ArrayList or LinkedList...
For example...
List<String> listOfStrings = new ArrayList<String>(25);
List<String> anotherListOfStrings = new LinkedList<String>();

List is an interface, essentially providing a list of operations (add, remove, get...), but no implementation (you cannot do new List). There are several classes implementing List interface, including ArrayList (using, as said, an array as internal container) and, for instance, LinkedList. You can instantiate these, instead, and write:
List<ElementType> myList = new ArrayList<ElementType>();
Using List as a type for myList reduces the effort if you want to replace ArrayList with LinkedList:
List<ElementType> myList = new LinkedList<ElementType>();
(immagine, instead, if you had to replace ArrayList with LinkedList in several places, instead). Additionally, you will hide the actual implementation lying behind, so that other programmers don't make tricky assumptions on how the List might behave.

Related

When declaring a List and assigning it to a LinkedList or ArrayList, are the different performance benefits still retained?

Take the following two lines of code:
List<String> listOfStrings = new ArrayList<>();
List<String> listOfStrings2 = new LinkedList<>();
I understand that it's good practice to program to Interfaces, however as a newbie, I'm trying to understand since we can only call List methods on both these instances, do they still "behave" like ArrayLists or LinkedLists (As in they perform like their respective classes when sorting/adding etc.)
Yeah they do behave like ArrayList or LinkedList, you can use this to save more different Lists (or your own objects) and call different implementations of the superclass's methods while iterating over an Array.
Both LinkedList and ArrayList implemented List, Collection, Iterable... interfaces, but they have different implementation of methods (like add(), remove(), etc. Arraylist and LinkedList will have different behavior/performance due to different implementations, when calling these methods).

List versus ArrayList [duplicate]

This question already has answers here:
Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"? [duplicate]
(8 answers)
Closed 5 years ago.
Which one is better and why ?
a) List<String> list = new ArrayList<>();
b) ArrayList<String> list = new ArrayList<>();
It depends on the context.
If you care only about the list semantics and not for the particular implementation, go for List<String>. If you want to enforce a particular implementation, go for ArrayList<String>, LinkedList<String> or anything else.
In most cases, you will want to go on with the interface and not the particular implementation.
(a) is better because it is more flexible. If for example, suddenly your requirement changes and says "Instead of creating a new empty array list to assign to the variable list, we will populate the list with items filtered from another list", you need to change your code for that. You might change it to something like this:
List<String> list = anotherList.stream().filter(x -> x.length() > 2).collect(Collectors.toList());
Since collect(Collectors.toList()) returns a List, you also need to change the type of list if you were using the code in (b).
Another situation is that later on you found out that you need to assign some other kind of list e.g. LinkedList to list. If you were using the code in (a), you can just assign the linked list straight away. If you were using the code in (b), you will have to go back to the declaration of list and change the type.
The general pattern is that as you use more "abstract" types, your code becomes more flexible but at the same time you can do less with your variables. For example, you can't use methods declared only in ArrayList on your list variable, but on the other hand, other kinds of lists can be assigned to list. If you an even more abstract type, Collection, then you can't use the members only declared in List anymore, but then all kinds of collections - Set, Map etc - can be assigned.

When do I use List and when do I use ArrayList, also LinkedList in Java? [duplicate]

This question already has answers here:
When to use LinkedList over ArrayList in Java?
(33 answers)
Closed 8 years ago.
When do I use List and when do I use ArrayList in Java? Please phrase in terms of practical situations where you would rather apply one over another. Thank you!
Edit : Also, LinkedList. Business situations where these are used, thanks, thats what's different about this question.
List is an interface. The other two are implementations of which.
You mostly want to code against interfaces. That is you wil do something like
List<String> strList = new ArrayList<String>();
Later on in the coding process, you may find that LinkedList has better performance for your scenario, so you just need to change one single place. Or maybe you don't care which concrete implementation is used, you just need "some sort of list". Then you could use an injected List implementation. Like this:
class ExampleClass{
private List<String> strList = null;
// We don't know and we don't care if Array or Linked List.
public ExampleClass( List<String> aList ){
strList = aList;
}
//...
}
For the differences between the implementations, see the links given in the comments as "possible duplicate of ..." or the JavaDoc.
***There's no difference between list implementations in both of your
examples. There's however a difference in a way you can further use
variable myList in your code.
When you define your list as:
List myList = new ArrayList(); you can only call methods and reference
members that belong to List class. If you define it as:
ArrayList myList = new ArrayList(); you'll be able to invoke ArrayList
specific methods and use ArrayList specific members in addition to
those inherited from List.
Nevertheless, when you call a method of a List class in the first
example, which was overridden in ArrayList, then method from ArrayList
will be called not the one in the List.
That's called polymorphism. You can read upon it.***
This answer was given by ATrubka here

Difference between Collection and Arraylist in Java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the benefit of polymorphism using Collection interface to create ArrayList object?
ArrayList al=new ArrayList();
Collection c=new ArrayList();
What is difference between object al and c? Are both of them are same or what?
The Collections API is a set of classes and interfaces that support operations on collections of objects.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
Whereas,
ArrayList: It is re-sizable array implementation. Belongs to 'List' group in collection. It permits all elements, including null. It is not thread -safe.
Collections: It implements Polymorphic algorithms which operate on collections.
Collection: It is the root interface in the collection hierarchy.
The following interfaces (collection types) extends the Collection interface:
List
Set
SortedSet
NavigableSet
Queue
Deque
Java does not come with a usable implementation of the Collection interface, so you will have to use one of the listed subtypes. The Collection interface just defines a set of methods (behaviour) that each of these Collection subtypes share. This makes it possible ignore what specific type of Collection you are using, and just treat it as a Collection. This is standard inheritance, so there is nothing magical about, but it can still be a nice feature from time to time.
The second is coding to interfaces. It allows the ArrayList to be swapped for another Collection (e.g. Vector or TreeSet) without any side effects.
Same object is created, but reference is different.
So in second case you can work with your ArrayList only as if it is just Collection, unless casting.
Collection is an Interface. Look at the methods.
List interface has methods to access by index. List also extends Collection interface.
ArrayList is a concrete implementation that implements List interface. ArrayList
What you are doing is some abstraction.
If you do :
Collection foo = new ArrayList();
you wont have access to List interface methods. such as accessing with index.
In al you are blocked to use only arraylists. You can't convert/cast anything but for arraylist.
In c you can convert/cast any class which implements the Collection interface.

Should I use ArrayList<?> or List<?>

I'm developing for Android and wondered, what are the main differences between an ArrayList and a List?
For the handling of objects collection in Java, Collection interface have been provided. This is available in java.util package.
"List" is an interface, which extends collection interface, provides some sort of extra methods than collection interface to work with collections. Where as "ArrayList" is the actual implementation of "List" interface.
The ArrayList class has only a few methods in addition to the methods available in the List interface. There is not much difference in this. The only difference is, you are creating a reference of the parent interface in the first one and a reference of the class which implements the List (i.e) the ArrayList class in the second. If u use the first, you will be able to call the methods available in the List interface and you cannot make calls to the new methods available in the ArrayList class.Where as, if you use the second one, you are free to use all the methods available in the ArrayList.
EDIT:
In Java Applications development, when you are supposed to pass the collection framework objects as arguments to the methods, then it is better to go with
List tempList = new ArrayList();
somemethodcall(tempList);
because, in future due to performance constraints, if you are changing the implementation to use linkedlist or some other classes which implements List interface, instead of ArrayList, you can change at only one point (i.e) only the instantiation part. Else you will be supposed to change at all the areas, where ever, you have used the specific class implementation as method arguments.
user370305 gives an exact explanation. This may also help you understand the collections hierarchy in Java.
List is interface which ArrayList implements. If you are trying to create a method which needs a List of some kind but you are not bothered what implemntation is actually used then use List.
If you are actually instantiating a class then you have to pick some implementation of List one of which is ArrayList
List<String> l1 = new ArrayList<String>();
would be an example.
You can not instantiate an interface and so would get an error if you tried to do the following:
List<String> l2 = new List<String>();
There is a good article on wikipedia about that, where the arraylist is called "dynamic array".
If you are trying to optimize your application you should take a look at the table next to the article.
List is an interface and ArrayList is an implementation of the List interface. The ArrayList class has only a few methods in addition to the methods available in the List interface.
Have a look at the short article on JavaBeat - Difference Between List and ArrayList?

Categories