wood burning stoves*
The moose likes Beginning Java and the fly likes List question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "List question" Watch "List question" New topic
Author

List question

Jacob Collins
Greenhorn

Joined: Jun 14, 2006
Posts: 8
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

Joined: Jul 08, 2003
Posts: 24183
    
  34

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.


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: List question
 
Similar Threads
ArrayList Problem(s)
tiger - doubt in this code ...
Why create ArrayList of type List?
Queue
Need help with generics( was Unwinding Generics -Part 1)