• Post Reply Bookmark Topic Watch Topic
  • New Topic

What is difference between these declaration?  RSS feed

 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is difference ?
Which one should we use and Why ?

Collection<Integer> c=new ArrayList<>();
List<Integer> ls=new ArrayList<>();
ArrayList<Integer> arr=new ArrayList<>();

I found some answers for this question but still not clear.
Answer is "Programming to interface not implementation".
 
Marshal
Posts: 56610
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
They are not simple declarations but declarations and initialisations. The <> without writing in between only works in Java7+.

In the last instance you are committing to using an array list. You cannot change to a different kind of List (e.g. linked list). You cannot assign that reference to any other sort of List, least of all something returned from a toList() method. You are programming to the implementation and restricting yourself by removing future flexibiltiy.
In the middle line you are programming to the interface; you can use any type of List. You can use any method in the List interface. Unfortunately you can't use array list‑specific methods like ensureCapacity. That last method is an example of how inheritance can go wrong. By programming to the interface however you retain future options and flexibility. You can reassign that reference to a linked list or what is returned from toList().
The first line is again programming to the interface. But you are using a superinterface, whose specification is less well‑defined. You cannot use List‑specific methods like get(), because they are not in the Collection interface. You can reassign that reference to a different kind of Collection. e.g. a set. Look at the difference between the add method in the List interface, the Set interface and the Collection interface. Note that Collection was intentionally given a vague specification which List and Set make more specific.

Remind yourself of the interfaces by reading the Java™ Tutorials. Go through the Set and List interfaces and see how many methods are not marked “specified by”. I think you will only find such methods in List.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!