J.5.1. ArrayList and Iterator

Figure J.2 uses an ArrayList (introduced in Section E.12) to demonstrate several capabilities of interface Collection. The program places two Color arrays in ArrayLists and uses an Iterator to remove elements in the second ArrayList collection from the first.


 1   // Fig. J.2: CollectionTest.java
 2   // Collection interface demonstrated via an ArrayList object.
 3   import java.util.List;
 4   import java.util.ArrayList;
 5   import java.util.Collection;
 6   import java.util.Iterator;
 7
 8   public class CollectionTest
 9   {
10      public static void main( String[] args )
11      {
12         // add elements in colors array to list
13         String[] colors = { "MAGENTA", "RED", "WHITE", "BLUE", "CYAN" };
14         List< String > list = new ArrayList< String >();
15
16         for ( String color : colors )
17            list.add( color ); // adds color to end of list
18
19         // add elements in removeColors array to removeList
20         String[] removeColors = { "RED", "WHITE", "BLUE" };
21         List< String > removeList = new ArrayList< String >();
22
23         for ( String color : removeColors )
24            removeList.add( color );
25
26         // output list contents
27         System.out.println( "ArrayList: " );
28
29         for ( int count = 0 ; count < list.size(); count++ )
30            System.out.printf( "%s ", list.get( count ) );
31
32         // remove from list the colors contained in removeList
33         removeColors( list, removeList );
34
35         // output list contents
36         System.out.println( " ArrayList after calling removeColors: " );
37
38         for ( String color : list )
39            System.out.printf( "%s ", color );
40      } // end main
41
42      // remove colors specified in collection2 from collection1
43      private static void removeColors( Collection< String > collection1,
44         Collection< String > collection2 )
45      {
46         // get iterator
47         Iterator< String > iterator = collection1.iterator();
48
49         // loop while collection has items
50         while ( iterator.hasNext() )
51         {
52            if ( collection2.contains( iterator.next() ) )
53               iterator.remove(); // remove current Color
54         } // end while
55      } // end method removeColors
56   } // end class CollectionTest

ArrayList:
MAGENTA RED WHITE BLUE CYAN

ArrayList after calling removeColors:
MAGENTA CYAN


Fig. J.2 | Collection interface demonstrated via an ArrayList object.

Lines 13 and 20 declare and initialize String arrays colors and removeColors. Lines 14 and 21 create ArrayList<String> objects and assign their references to List<String> variables list and removeList, respectively. We refer to the ArrayLists in this example via List variables. This makes our code more flexible and easier to modify. If we later decide that LinkedLists would be more appropriate, we’ll need to modify only lines 14 and 21 where we created the ArrayList objects.

Lines 16–17 populate list with Strings stored in array colors, and lines 23–24 populate removeList with Strings stored in array removeColors using List method add. Lines 29–30 output each element of list. Line 29 calls List method size to get the number of elements in the ArrayList. Line 30 uses List method get to retrieve individual element values. Lines 29–30 also could have used the enhanced for statement (which we’ll demonstrate with collections in other examples).

Line 33 calls method removeColors (lines 43–55), passing list and removeList as arguments. Method removeColors deletes the Strings in removeList from the Strings in list. Lines 38–39 print list’s elements after removeColors completes its task.

Method removeColors declares two Collection<String> parameters (lines 43–44) that allow any two Collections containing strings to be passed as arguments to this method. The method accesses the elements of the first Collection (collection1) via an Iterator. Line 47 calls Collection method iterator to get an Iterator for the Collection. Interfaces Collection and Iterator are generic types. The loop-continuation condition (line 50) calls Iterator method hasNext to determine whether the Collection contains more elements. Method hasNext returns true if another element exists and false otherwise.

The if condition in line 52 calls Iterator method next to obtain a reference to the next element, then uses method contains of the second Collection (collection2) to determine whether collection2 contains the element returned by next. If so, line 53 calls Iterator method remove to remove the element from the Collection collection1.


Image Common Programming Error J.1

If a collection is modified after an iterator is created for that collection, the iterator immediately becomes invalid—operations performed with the iterator after this point throw ConcurrentModificationExceptions. For this reason, iterators are said to be “fail fast.”


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset