4

So I can't seem to figure out the difference between these two code snippets, or when one would be preferred over the other. Snippet #1

  public static void main(String[] args) {
           List testList = new ArrayList();
           testList.add(new Integer(6));

           String string = (String) testList.get(0);
     }

Snippet #2

public static void main(String[] args) {
       ArrayList testList = new ArrayList();
       testList.add(new Integer(6));

       String string = (String) testList.get(0);
   }

My interpretation was that in snippet 1, a List named testList is being assigned to an ArrayList object. And in snippet 2 an ArrayList named testList is being assigned to an ArrayList object. However that just doesnt make sense to me.

Side question: Is one of the two a preferred standard?

john woolstock
  • 177
  • 1
  • 7
  • I think this questions might have some duplicates – user1231232141214124 Nov 23 '15 at 21:25
  • 3
    Both are bad since you are using raw-types instead of generics, and you are trying to read Integer as String (generics would protect you agains this mistake). Anyway first snippet is little better because you are programming on interfaces (we used `List` as type or `testList` interface since we doesn't really care how that list is implemented which gives us flexibility to change that implementation later if we want). – Pshemo Nov 23 '15 at 21:25
  • See this [article](http://www.fatagnus.com/program-to-an-interface-not-an-implementation) for more info. – MaxZoom Nov 23 '15 at 21:28
  • Interfaces, amongst other things, allow you more flexibility in the future (if you need to change the type of collection you are dealing with) – blurfus Nov 23 '15 at 21:29
  • Thank you very much for the article link, alot of confusion cleared in a few minutes of reading. Awesome article. @MaxZoom – john woolstock Nov 23 '15 at 21:34
  • @johnwoolstock Lots of `hard to grasp at first` concepts, but after a while it becomes second nature. See also [this one](http://www.artima.com/lejava/articles/designprinciples.html) for more reasons. – MaxZoom Nov 23 '15 at 21:48

2 Answers2

1

List is an interface. ArrayList implements List. So, functionally, both the snippets work same way.

Aragorn
  • 5,021
  • 5
  • 26
  • 37
1

The first snippet uses the interface List type, the second one uses the object type ArrayList.

Unless you really need any methods coming from ArrayList, you should use the interface type to prevent confusion about types.

GiantTree
  • 218
  • 3
  • 13