4

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gautam Savaliya
  • 1,403
  • 2
  • 20
  • 31

5 Answers5

12

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.

code_fish
  • 3,381
  • 5
  • 47
  • 90
  • This is in my opinion not an answer to the "trivial question". It does not explain why the objects al and c are fundamentally different. – Marcos Gonzalez Feb 17 '18 at 23:36
4

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.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
3

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.

Nikolay Kuznetsov
  • 9,467
  • 12
  • 55
  • 101
2

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.

DarthVader
  • 52,984
  • 76
  • 209
  • 300
2

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
someone
  • 6,577
  • 7
  • 37
  • 60