0

What is the purpose of specifying different types on the left and the right side in Java variable declarations?

For example, code like this is standard:

List<String> l = new ArrayList<>();

Why don't:

ArrayList<String> l = new ArrayList<>();

or

Object l = new ArrayList<>(); // Silly example but shows two extremes
user3139545
  • 6,882
  • 13
  • 44
  • 87
  • in short: abstraction – jamp Apr 23 '15 at 08:14
  • @RaulRene the question is not about the generics here... – jamp Apr 23 '15 at 08:16
  • 1
    we can always use `ArrayList l = new ArrayList<>();` there is nothing wrong. It only depends on how you want to use it. Also `Object l = new ArrayList<>(); ` is also correct depending on the use. – Blip Apr 23 '15 at 08:17
  • Also duplicates: http://stackoverflow.com/questions/1348199/java-hashmap-vs-map-objects – T.J. Crowder Apr 23 '15 at 08:17
  • I feel could you clarify what you exactly want to ask?\ – Blip Apr 23 '15 at 08:18
  • 1
    @Blip as a rule of thumb, variable types should be the most general type possible as (among other things) doing so reduces coupling. With `List`s this means your declaration should be `List strings = new ArrayList<>()` (or better `Collection` strings = new ArrayList<>()`) - the T.J. Crowder's answer in the duplicate explains this. – Nick Holt Apr 23 '15 at 08:43

2 Answers2

1
  • This List<String> l = new ArrayList<>(); allows you to instantiate all types of List, be it ArrayList or LInkedListof String. You can use all methods of List
  • ArrayList<String> l = new ArrayList<>(); you can only instantiate ArrayList of String.
  • Object l = new ArrayList<>(); you cannot use List methods.
Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
1

When you do this, you cannot use list operations like add(), remove(), addAll(), etc.

Object l = new ArrayList<>();

Here, you are loosing the flexibility of polymorphism:

ArrayList<String> l = new ArrayList<>();// later you could not re-initialize
l = new LinkedList<String>();//compile time error
  • re-initialization like that could cause side-effects and more. IMHO it is bad practice to do things like that. – B. Kemmer Apr 23 '15 at 08:27
  • @B.Kemmer that's true but not the point. Instead of re-initialization you should think of changing the implementation to a LinkedList. That would probably require more code changes if you declared as ArrayList than as the List interface. – Adriaan Koster Apr 23 '15 at 08:41
  • @Adriaan Koster The point is that List does prevent a lot of trouble. For example it's easier to add unit tests to your code etc. Check this post for further informations http://www.javaworld.com/article/2073649/core-java/why-extends-is-evil.html – B. Kemmer Apr 23 '15 at 08:48
  • @B.Kemmer I already got the point. You commented on re-initialization being bad practice which is not relevant to the discussion. – Adriaan Koster Apr 23 '15 at 09:15