Re: List Interfaces
Alper wrote:
Hello people,
I start programming with java 2 months ago and it goes pretty well for
now. I was exploring the Collections Interface and I have a question
about it.
Why would u use this line;
List list = new ArrayList();
Instead of this one;
ArrayList alist = new ArrayList();
I know that in the first one, we create a list reference variable and
assigned it to the new ArrayList instance and I know that I can only
use the methods of list but not arraylist. but why would i need List
reference while i can use ArrayList reference? I mean what's the
benefit of using List reference or Collection Reference when creating
an ArrayList Instance?
If you use the List reference, the rest of your program
can use only the methods that every List provides and cannot
use methods that are only provided by ArrayList. This may
sound like a disadvantage -- why would you want to ignore
the perfectly good features of ArrayList? -- but it can turn
out to be an advantage in the long run. Here's the scenario:
You write your code using an ArrayList. Fine and dandy,
but you notice that your code makes a lot of insertions and
deletions in the middle of the list, and this forces the
ArrayList to spend a lot of time shifting things back and
forth in its internal array to make room for new items or
squeeze out the space formerly occupied by removed items.
"Aha!" you think, "a LinkedList can do these middle-of-the-list
operations without all that overhead. I'll change my code to
use a LinkedList instead of an ArrayList."
If you used a List reference, you can make this change by
altering just one line of code: write `new LinkedList()' instead
of `new ArrayList()', and you're finished. Nothing needs to
change anywhere else in your code; it just keeps working. And
if you later decide the LinkedList was a bad idea, you can revert
to ArrayList just by changing that one line again. You can even
write a special-purpose AlpersList class that's carefully tuned
for your program's activity patterns, and plug it into your
existing code with a one-line change.
Now, if you actually *need* some of the special capabilities
provided by ArrayList but not provided by generic List, go ahead
and use an ArrayList variable. There'd be no question of changing
to a LinkedList or AlpersList anyhow, so there's no point in
trying to make the change easy. But if your needs are satisfied
by the generic List interface, you may as well use a List variable
so you keep the freedom to plug in different kinds of Lists at a
later date.
--
Eric Sosman
esosman@acm-dot-invalid.org