Section 11.7. Lists

   

11.7 Lists

Java lists allow you to perform the same kinds of operations that ColdFusion lists do. Lists have these chief characteristics:

  • Lists store their data in an ordered fashion known as a sequence.

  • Because the data is ordered, you can refer to individual elements by position. Position is an integer index.

  • Lists allow duplicate elements. This is in contrast to other types of collections, such as sets, which do not allow duplicates.

  • Lists are zero-based like Java arrays. This is in contrast to a ColdFusion list, the first element of which has an index of 1.

11.7.1 LinkedList

The LinkedList is much like an ArrayList (discussed below). It offers a way to store objects each in their own link. A link stores a reference to the prior and next links in the sequence. Therefore data is stored in a linked list as ordered without ordinal index assignment. This makes the LinkedList much faster when you need to remove data from, or insert data into, the middle of the list.

The following listing demonstrates this collection:

11.7.2 LinkedListTest.java

 package chp11;  import java.util.LinkedList; import java.util.*; public class LinkedListTest {     public static void main(String[] a ) {         LinkedList employees = new LinkedList();             // add items to the linked list         employees.add("Colonel Pickering");         employees.add("Eliza Doolittle");         employees.add("Henry Higgins");             // get an iterator. Notice that this is a method             // of the LinkedList class, not a new object         Iterator it = employees.iterator();         for (int i = 0; i < 3; i++) {             System.out.println(it.next());         }     } } 

The similiar operation in ColdFusion would use a list. That's because there are no key names for the values in the collection:

 <cfset employees = "Colonel Pickering, Eliza Doolittle, Henry Higgins">  <cfloop from = "1" to = "3" index="i"> <cfoutput>#ListGetAt(employees,  i,  ",")#<br></cfoutput> </cfloop> 

This could be written in ColdFusion script as well, in a syntax that is closer to Java:

 <cfscript>  employees = "Colonel Pickering, Eliza Doolittle, Henry Higgins"; for (i = 1; i lte 3; i = i + 1) { this = ListGetAt(employees, i, ","); WriteOutput(this & "<br>"); } </cfscript> 

The output in all of the above cases is:

 Colonel Pickering  Eliza Doolittle Henry Higgins 

Note that this is a keyword in Java and JavaScript, but not ColdFusion.

11.7.3 ArrayList

An ArrayList is an implementation of the List interface that provides a resizeable array. Here are the chief characteristics of the ArrayList :

  • They are not synchronized. If you want a synchronized version, use a Vector .

  • ArrayList s have a capacity, which is the number of cells required to store the elements in the list.

  • An ArrayList is resizeable. The capacity will grow automatically when you add elements to the list.

  • If you need to add a large number of elements to the list all at once, you can increase performance by using the ensureCapacity() method.

Note that there is a ColdFusion function called ArrayResize , whose purpose is to resize an array to the specified number of elements. You use this in ColdFusion only when you require an array with more than 500 elements. This function is similar to the ensureCapacity() function in Java, in that it is only used when adding large amounts of data.

11.7.4 ArrayListTest.java

 package chp11;  import java.util.ArrayList; import java.util.Iterator; public class ArrayListTest {     public static void main(String [] a) {             // create arraylist         ArrayList vegetables = new ArrayList();         vegetables.ensureCapacity(5);             // populate it         Iterator it = vegetables.iterator();         String[] names = {"carrots", "yams", "beans"};         for (int i = 0; i < names.length; i++) {             vegetables.add(i, names[i]);         }         System.out.println("List size: " + vegetables.size());             // get second element in the array:         System.out.println(names[1]);             // get second element in the ArrayList:         System.out.println(vegetables.get(1));         String otherveg = "beans";         boolean result = otherveg.equals(vegetables.get(2)) ? true : false;             // returns true         System.out.println("Are the items in pos. 2 equal? " +  result);     } } 

The output of this program is:

 List size: 3  yams yams Are the items in pos. 2 equal? true 

Note

The similar operation in ColdFusion would use a regular array. Remember that ColdFusion arrays start at 1, not 0.


It is preferable to use a LinkedList when you need to update items in the middle of a list, and your list contains a large number of elements. Otherwise, the performance increase you get is negligible, and you can use an ArrayList .

11.7.5 Sorting

It is useful on occasion to sort the data you have stored in a list type collection. You can do this using the Collection sort() method, as shown below.

11.7.6 SortTest.java

 package chp11;  import java.util.*; public class SortTest {     public static void main(String[] a) {             // create new list of the specified             // size         ArrayList employees =             new ArrayList(Arrays.asList(new String[6]));         String defaultName = "Jason";         Collections.fill(employees, defaultName);             // now all 5 employees elements are filled             // with "Jason"             // add some other employees         employees.set(1, "Quentin");         employees.set(3, "Caddie");         employees.set(5, "Benji");             // implicit toString() called         System.out.println("Unsorted: " + employees);             // sort them         Collections.sort(employees);         System.out.println("Sorted: " + employees);     } } 

The output is as follows :

 Unsorted: [Jason, Quentin, Jason, Caddie, Jason, Benji]  Sorted: [Benji, Caddie, Jason, Jason, Jason, Quentin] 

11.7.7 Vector

A Vector is used to store an array of object references that can grown automatically as needed. Originally, Vector was a direct descendant of java.lang.Object . With the many aspects of Java that were redesigned in version 1.2, Vector was changed to extend java.util.AbstractList .

The Java standard classes use vectors extensively. For instance, in GUI applications using PopupMenus , vectors are under the hood to store these objects in java.awt.Component .

Vector has a number of constructors, each of which are more or less useful depending on the problem at hand. Here are the Vector constructors:

  • Vector() Constructs an empty vector. Its internal data array has a size of 10.

  • Vector(Collection c) Constructs a vector containing all of the elements of the collection specified, in the order their iterator returns them.

  • Vector(int initialCapacity) Constructs an empty vector with the initial capacity specified.

  • Vector(int initialCapacity, int capacityIncrement) Constructs an empty vector with the initial capacity and capacity increment as specified.

11.7.7.1 ACCESSING AND SEARCHING VECTOR ELEMENTS

The object references in a vector are stored as an array. That means you can retrieve their values using an int index. Like arrays, the Vector index starts at 0. There are a number of methods made available to allow you to find specific elements and search through a vector:

  • firstElement() returns the object reference for the element at index 0.

  • indexOf(Object o) searches for the first occurrence of the specified object, similar to how you might use ListFind() in ColdFusion. ListFind() returns a number indicating the element's ordinal place in the list. By the same token, indexOf() returns an int .

  • subList(int fromIndex, int toIndex) returns a List containing the portion of the list elements residing between the specified indices.

  • lastIndexOf(Object o) returns the index of the last occurrence of this element in the vector.

In the listing below, we add some elements to a vector, reference and remove one of them, and then send the vector to a string.

11.7.8 VectorTest.java

 package chp11;  import java.util.Vector; import java.util.StringTokenizer; public class VectorTest {     public static void main (String [] a) {     Vector v = new Vector();     for (int i = 0; i < 5; i++) {         v.add(i, new Integer(i+100));         System.out.println(v.get(i));     }         // remove the element at 2     Integer goner =  (Integer) v.remove(2);         // prove it     System.out.println("Item removed: " + goner);         // entire vector as a string     StringTokenizer st = new StringTokenizer(v.toString());     System.out.println("number of tokens: " + st.countTokens());        // print out these in token list     while (st.hasMoreTokens()) {         System.out.println(st.nextToken());     }     v.removeAll(v);     System.out.println("is it empty now? " + v.isEmpty());     } } 

The VectorTest.class program outputs the following:

 100 101 102 103 104 Item removed: 102 number of tokens: 4 [100, 101, 103, 104] is it empty now? true 

As you can see, you can use the collection methods add() and remove() with vectors.

Vectors cannot contain primitive values. We use this example as a reminder of this fact. We cannot simply store an int . We must create an Integer object to add it, and then unwrap it to reference it.

11.7.9 Stack

The Stack object is a special kind of vector (it extends Vector ). Its purpose is to provide an easy mechanism for last in, first out (LIFO) processing. This structure allows you to add elements to and remove elements from only the top of the stack. Inserting an element is called a push, while retrieving an element is called a pop. Just think of a deck of cards being dealt.

The main usefulness of Stack is for building lists that do not require frequent or heavy access. There are two ways that you can work with Stack . The first is with an iterator; the preferable way is with special methods for stacks:

  • push(Object o) pushes an object onto the top of the stack.

  • pop() removes the object at the top of the stack.

  • peek() looks at the first object on the stack.

  • search(Object o) looks for an object inside the stack. If the specified item is found,

  • empty() tests if the stack is empty.

As with Vector , you must remember to appropriately wrap and unwrap your primitives. Following is an example using a stack:

11.7.10 StackTest.java

 package chp11;  import java.util.Stack; public class StackTest {     public static void main (String [] a) {             // create stack         Stack s = new Stack();             // add items to stack, which             // requires Objects         s.push(new Double(1.00));         s.push(new Integer(99));             // which is on top?         System.out.println(s.peek());         Integer d1 = (Integer) s.pop();         Double d2 = (Double) s.pop();         System.out.println("d1: " + d1 + " d2: " +  d2);     } } 

The output looks like this:

 99 d1: 99 d2: 1.0 

The java.util.Stack discussed above is a subclass of Vector , a type of collection. These are used exclusively for data storage. There is another stack that is important in Java, the Call Stack. The Call Stack is used in the Java Virtual Machine for handling memory internally. Both stacks use the same kind of first in, last out data access.

11.7.11 Choosing a Data Storage Structure

You should be able to accomplish many of the data storage tasks you will commonly need using the List classes. It is not generally preferable to use vectors anymore, though you will see them a lot in legacy code. Remember that vectors are single threaded, and they can therefore be a source of bottlenecking in your applications. It is often smarter to use another type, even if you require synchronization. Also recall that vectors will expose an Enumeration object, and that it is preferable to use Iterator s now.

The legacy Hashtable class also returns an Enumeration object instead of an iterator. A Hashtable is very much like a HashMap . Methods of the Hashtable are synchronized. Because synchronizing at the method level instead of the object level creates greater overhead, you should probably use a HashMap instead if you do not require synchronization.

The List classes have many advantages, including easy resizing, element ordering, and the ability to easily insert and remove elements. The chief disadvantage with using lists is that you cannot store primitive values in them; storing wrapped primitives in them requires that a good deal of complexity and length be added to your work and hampers readability.

If you need to store only primitives, an array is the best choice. If you need to store any object type, a List is the best choice.


   
Top


Java for ColdFusion Developers
Java for ColdFusion Developers
ISBN: 0130461806
EAN: 2147483647
Year: 2005
Pages: 206
Authors: Eben Hewitt

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