ArrayList and the List Interface


In earlier lessons, you created ArrayList instances and assigned them to references of the ArrayList type:

 ArrayList<Student> students = new ArrayList<Student>(); 

The Java API documentation shows that ArrayList implements the List interface. If you browse the documentation for the List interface, you'll see that virtually all messages you had sent to ArrayList instances are defined in List. Thus, you should prefer defining students (in this example) as a List type:

 List<Student> students = new ArrayList<Student>(); 

The ArrayList class defines a fixed-length array in memory. Its performance characteristics are good unless you are constantly inserting or deleting elements that appear before the end of the list. If your list needs these characteristics, a linked list is the better data structure, since it uses more dynamic memory management. The downside is that accessing elements in a linked list is done by serially traversing the list from the beginning, whereas accessing an element in an array is immediate, since it only needs to calculate an offset from the beginning of the memory block.

Java's implementation of a linked list is provided as java.util.LinkedList. If you use the List reference type throughout your code, you could change the performance characteristics of your application by making a change in one place:

 List<Student> students = new LinkedList<Student>(); 

For now, go through your source code and change as many references as possible to be an interface type.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net