Difference between Collection and Arraylist in Java? [duplicate] - java

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.

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 & ArrayList in Java [duplicate]

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.

Difference between ArrayList<Integer> list = new ArrayList<Integer>(); and Collection<Integer> list1 = new ArrayList<Integer>();

I don't understand difference between:
ArrayList<Integer> list = new ArrayList<Integer>();
Collection<Integer> list1 = new ArrayList<Integer>();
Class ArrayList extends class which implements interface Collection, so Class ArrayList implements Collection interface. Maybe list1 allows us to use static methods from the Collection interface?
An interface has no static methods [in Java 7]. list1 allows to access only the methods in Collection, whereas list allows to access all the methods in ArrayList.
It is preferable to declare a variable with its least specific possible type. So, for example, if you change ArrayList into LinkedList or HashSet for any reason, you don't have to refactor large portions of the code (for example, client classes).
Imagine you have something like this (just for illustrational purposes, not compilable):
class CustomerProvider {
public LinkedList<Customer> getAllCustomersInCity(City city) {
// retrieve and return all customers for that city
}
}
and you later decide to implement it returning a HashSet. Maybe there is some client class that relies on the fact that you return a LinkedList, and calls methods that HashSet doesn't have (e.g. LinkedList.getFirst()).
That's why you better do like this:
class CustomerProvider {
public Collection<Customer> getAllCustomersInCity(City city) {
// retrieve and return all customers for that city
}
}
What we're dealing with here is the difference between interface and implementation.
An interface is a set of methods without any regard to how those methods are implemented. When we instantiate an object as having a type that is actually an interface, what we're saying is that it is an object that implements all of the methods in that interface... but doesn't provide is with access to any of the methods in the class that actually provides those implementations.
When you instantiate an object with the type of an implementing class, then you have access to all of relevant methods of that class. Since that class is implementing an interface, you have access to the methods specified in the interface, plus any extras provided by the implementing class.
Why would you want to do this? Well, by restricting the type of your object to the interface, you can switch in new implementations without worrying about changing the rest of your code. This makes it a whole lot more flexible.
The difference, as others have said, is that you are limited to the methods defined by the Collection interface when you specify that as your variable type. But that doesn't answer the question of why you would want to do this.
The reason is that the choice of data type provides information to the people using the code. Especially when used as the parameter or return type from a function (where outside programmers may have no access to the internals).
In order of specificity, here is what different type choices might tell you:
Collection - a group of objects, with no further guarantees. The consumer of this object can iterate over the collection (with no guarantees as to iteration order), and can learn its size, but cannot do anything else.
List - a group of objects that have a specific order. When you iterate over these objects, you will always get them in the same order. You can also retrieve specific items from the collection by index, but you cannot make any assumptions about the performance of such retrieval.
ArrayList - a group of objects that have a specific order, and may be accessed by index in constant time.
And although you didn't ask about them, here are some other collection classes:
Set a group of objects that is guaranteed to contain no duplicates per the equals() method. There are no guarantees regarding the iteration order of these objects.
SortedSet a group of objects that contains no duplicates, and will always iterate in a specific order (although that specific order is not guaranteed by the collection).
TreeSet a group of ordered objects with no duplicates, that exhibits O(logN) insert and retrieval times.
HashSet a group of objects with no duplicates, that does not have an inherent order, but provides (amortized) constant-time access.
The only difference is that you're providing access to list1 through the Collection interface, whereas you provide access to list2 through the ArrayList interface. Sometimes, providing access through a restricted interface is useful, in that it promotes encapsulation and reduces dependence on implementation details.
When you perform operations on "list1", you'll only be able to access methods from the Collection interface (get, size, etc.). By declaring "list" as an ArrayList, you gain access to additional methods only defined in the ArrayList class (ensureCapacity and trimToSize, for example.
It's typically best practice to declare the variable as the least specific class you need. So, if you only need the methods from Collection, use it. Typically in this case, that would mean using List, which lets you know it's ordered and can handle duplicates.
Using the least specific class/interface allows you to freely change the implementation later. For example, if you later learn that a LinkedList would be a better implementation to use, you could change it without breaking all your code if you define the variable to be a List.

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?

Call addFirst on a Collection

Collection col = new LinkedList();
Is there a way to call col.addFirst ?
Yes, if you cast to LinkedList:
((LinkedList) col).addFirst(..)
But this is discouraged, because you don't always know the concrete type of the collection. You can check with instanceof, but that is not good object oriented code. If you really require a LinkedList, require a LinkedList (rather than Collection)
If you declare a variable as Collection, this means that you normally plan to consider this variable, in the rest of your program, as a simple Collection, and not as a linked list. The methods offered by the Collection interface should be sufficient for the rest of your program using this variable.
If you need access to a specific method only present in the LinkedList class, then the variable should be a declared as LinkedList.
I am not sure why you need to use Collection in this case, however you can still "program to an interface and not to an implementation" if you use the interface java.util.Deque which, by chance, also extends java.util.Collection
Deque<String> deque = new LinkedList<String>();
deque.addFirst("Hello");
Collection<String> collection = deque;
If you use List instead of Collection, then the .add() method is available. Add at index 0 to put it in on the first position.
list.add(0, object)

Categories