Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / October 2006

Tip: Looking for answers? Try searching our database.

List Interfaces

Thread view: 
Alper - 08 Oct 2006 16:02 GMT
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?

Thx for ur help :)
Thomas Fritsch - 08 Oct 2006 16:27 GMT
> Hello people,
>
[quoted text clipped - 18 lines]
>
> Thx for ur help :)

By using
 List list = new ArrayList();
you restrict yourself to use only those methods of ArrayList which are
specified in List. You can't for example use
 list.trimToSize();
or
 list.ensureCapacity(50);
because these methods are defined only in ArrayList, but not in List.
The benefit of this is, that you later could easily change your
implementation from ArrayList to another type of List (for example to
LinkedList or Vector) just by changing that one line from
 List list = new ArrayList();
to
 List list = new LinkedList();
or

 List list = new Vector();

Signature

Thomas

Pawel Szulc - 08 Oct 2006 16:43 GMT
to summerize the principal here is to use interfaces more then exact
class to get flexibility of modyfing your program. this is of course
more a guideline then a rule but is well used among programmers

>   List list = new ArrayList();
> to
>   List list = new LinkedList();
> or
>
>   List list = new Vector();
Eric Sosman - 08 Oct 2006 17:05 GMT
> Hello people,
>
[quoted text clipped - 16 lines]
> 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.

Signature

Eric Sosman
esosman@acm-dot-invalid.org

Alper - 08 Oct 2006 17:29 GMT
Thank all of you for answers :)

I think I understand it now. I was thinking that Interfaces are just
for multiple inheritance or just a abstact class. I guess it is more of
them. Interfaces come to rescue when programmers need flexibility.
Arne Vajhøj - 08 Oct 2006 19:55 GMT
> I think I understand it now. I was thinking that Interfaces are just
> for multiple inheritance or just a abstact class. I guess it is more of
> them. Interfaces come to rescue when programmers need flexibility.

The OOP buzzword is "encapsulation".

Arne
Paul Tomblin - 08 Oct 2006 22:21 GMT
In a previous article, Eric Sosman <esosman@acm-dot-org.invalid> said:
>     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:

Other than the one you mentioned, another reason I have for using List
instead of ArrayList is that sometimes I find that my ArrayList is getting
updated in multiple threads, and so I can switch to a synchronized class
by changing
   List list = new ArrayList();
to
   List list = new Vector();
or
   List list = Collections.synchronizedList(new ArrayList());

Signature

Paul Tomblin <ptomblin@xcski.com> http://blog.xcski.com/
If you drink Real beer, you become horizontal... so, if you
drink Imaginary beer, you become vertical...
             -- Thorfinn

Ed - 08 Oct 2006 23:04 GMT
Alper skrev:

> Hello people,
>
[quoted text clipped - 9 lines]
>
> ArrayList alist = new ArrayList();

Aside from the fine answers you've received, there's little reason to
choose your first example over your second in a method body, for
example:

private void test() {
  List customers = new ArrayList();
  customers = addPaymentOutstandingCustomers();
  sendLetterTo(customers);
}

It doesn't matter whether you use an ArrayList or a List in that
declaration, because if you change the ArryayList to a Vector, then the
following two lines don't change.

Where the principle of, "Program to an interface, not an
implementation," carries more weight in Java is in method declarations.
For example, if the sendLetterTo() method above should be declared as,

public void sendLetterTo(Collection collection);

So that the implementation of the collection can change without
affecting code. But it doesn't matter if, in the method body shown
above - and for this example - "customers" was declared as ArrayList or
List.

.ed

--

www.EdmundKirwan.com - Home of The Fractal Class Composition
Lew - 08 Oct 2006 23:40 GMT
> Where the principle of, "Program to an interface, not an
> implementation," carries more weight in Java is in method declarations.
[quoted text clipped - 6 lines]
> above - and for this example - "customers" was declared as ArrayList or
> List.

If I may add something without belaboring the point:

Choose the highest level class or interface that does want you want, but no
higher.

For example, if you need iteration in a particular order, Collection is too
general; you need List or SortedSet.

If you need to guarantee that duplicate entries cannot occur, you need a Set.

If you need to guarantee the performance characteristics of your collection,
you might require a particular implementation.  For example, among Sets the
HashSet "offers constant time performance for the basic operations (add,
remove, contains and size), assuming the hash function disperses the elements
properly among the buckets."
http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashSet.html

TreeSet "guarantees that the sorted set will be in ascending element order,
sorted according to the natural order  of the elements (see Comparable), or by
the comparator provided at set creation time, depending on which constructor
is used", but costs "log(n) time ... for the basic operations (add, remove and
contains)." (n is the set size.)
http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeSet.html

Others have mentioned that you declare the type that gives you the methods you
need; you also declare the type that gives you the behavior that you need.

- Lew


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.