6

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?

0

5 Answers 5

13

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
5

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.

Comments

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.

1 Comment

"The question is too easy", but only this answer hits the core of the issue.
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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.