• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

List question

 
Jacob Collins
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was wondering why a java programmer using LinkedList or ArrayList would make the pointer be of type List instead of ArrayList or LinkedList. What I mean is, why does a programmer do this:
List <Integer> myList = new LinkedList<Integer>();
intead of this:
LinkedList <Integer> myList = new LinkedList<Integer> ();

I see the first form more but I don't understand why programmers just don't use the second form.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose you use the LinkedList declaration. Several weeks later, you find that there's a performance problem, and using an ArrayList instead would be much faster. How much code do you have to change? What if LinkedList<Integer> were the return type of a frequently-called method?

Now suppose you used a List<Integer> declaration instead. How hard would the same change be?

So that's the basic answer. By making the type of a variable, parameter, or return value as general as possible, you isolate design decisions and make code easier to modify.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic