File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

List question

Jacob Collins

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

Joined: Jul 08, 2003
Posts: 24189

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:
subject: List question