The moose likes Beginning Java and the fly likes Lists with different typed reference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Lists with different typed reference" Watch "Lists with different typed reference" New topic

Lists with different typed reference

Nigel Skeffington

Joined: Mar 20, 2004
Posts: 7
Why do we see examples like:

List list = new ArrayList();
Collection list = new ArrayList();
ArrayList list = new ArrayList();

What is the advantage or disadvantage to these approaches? In the Sun tutorials, they use a combination of these.

Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

In general using the least specific applicable type for a variable gives you more flexibility.

For example, say you're writing a method that operates on a list of items. The list is to be passed in as an argument. If you declare the argument type to be ArrayList, then only callers who have an ArrayList full of items can use your method. What if they already have a LinkedList full of items to process? Even though ArrayList and LinkedList have virtually the same list of methods, your method won't work with a LinkedList. This is bad.

Instead, you could declare your method to accept an argument of type List, and use only the methods of the List interface in implementing your method. Now callers can pass in any kind of List at all -- your method is more useful, and all you did was erase a few letters!

You can make similar arguments about using general types within a single method. Using more general variable types makes it much easier to change a method to use a different specific type. ArrayList and LinkedList have very different performance characteristics. If you wrote a program using an ArrayList but later find that a LinkedList would be faster, it'd be nice to be able to make one change in one place and have everything work, right? Well, using the most general possible variable types enables this kind of simple change.

[Jess in Action][AskingGoodQuestions]
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
If you are interested in more information about this, you should use the Search tool. This question has been asked several times here and in the intermediate forum.


Java API Documentation
The Java Tutorial
Nigel Skeffington

Joined: Mar 20, 2004
Posts: 7
Ernest: Thank you for the thorough explaination. Now that I read it, it almost seems obvious, like I should have known.

Layne: Thanks for pointing that out. :roll:

I agree. Here's the link:
subject: Lists with different typed reference
jQuery in Action, 3rd edition