Summary


Java 5 Style Collections: Generics

The Java 5 platform introduced sweeping changes to the Java collections framework. The most important change was the introduction of Generics. Generics offer the ability to define the type of objects a collection contains when the collection is declared. Other changes include an enhanced for loop specifically designed to iterate over collections along with additional collection interfaces and classes.

Java 5 Collection Framework Core Interfaces

The Java 7 collections framework introduced additional core interfaces as shown in figure 17-21. The <E> to the right of each interface represents a type placeholder for the element type the collection will contain when it is created. For the Map and its sub interfaces the <K, V> represents the collection’s Key and Value type placeholders. New interfaces now include Queue<E>, BlockingQueue<E>, and ConcurrentMap<K, V>. These new interfaces and their characteristics are listed and described in table 17-2.

image from book
Figure 17-21: Java 5 Collections Framework Core Interface Hierarchy

Table 17-2: New Java 5 Core Collection Interfaces

Interface

Characteristic

Queue<E>

The Queue<E> interface represents a collection that holds elements prior to processing.

BlockingQueue<E>

A BlockingQueue<E> is a Queue<E> that is capacity bounded and can block on retrievals when the queue is empty or block on insertions when the queue is full.

ConcurrentMap<K, V>

The ConcurrentMap<K, V> interface is found in the java.util.concurrent package. It provides enhanced functionality in concurrent programming environments.

Java 5 Collections Framework Sample Programs

This section offers several examples of the Java 5 collections framework in action.

SetTestApp Program Revised

Let’s first take a look at a short program that uses generic collection classes. Example 17.13 offers a revised version of the SetTestApp class originally given in example 17.5.

Example 17.13: SetTestApp.java (generic version)

image from book
 1     import java.util.*; 2 3     public class SetTestApp { 4       public static void main(String[] args){ 5         List<Integer> list = new LinkedList<Integer>(); 6         for(int i=0; i<50; i++){ 7           list.add(i % 10); 8         } 9         System.out.print("List contents: "); 10 11        for(Iterator i = list.iterator(); i.hasNext();){ 12          System.out.print(i.next()); 13        } 14        System.out.println(); 15 16        Set<Integer> set = new TreeSet<Integer>(list); 17        System.out.print("Set contents: "); 18        for(Iterator i = set.iterator(); i.hasNext();){ 19          System.out.print(i.next()); 20        } 21 22        System.out.print("\nSet contents using for-each loop: "); 23        for(Integer i : set){ 24          System.out.print(i); 25        } 26      } // end main() 27    } // end SetTestApp class definition
image from book

Referring to example 17.13 — this version of SetTestApp uses Java generic collection classes and the enhanced for loop (for-each loop) to iterate over one of the collections. It would be helpful to compare this version of the program with the Java 1.4.2 version during this discussion.

The first change appears on line 5 where the specific element type that will be contained in the list is specified in the angle brackets. In this example the LinkedList will store elements of type Integer. The for loop beginning on line 6 has been modified to generate only 50 int values. Notice now, however, that it is no longer necessary to explicitly create Integer objects with the new operator because the primitive int values are automatically boxed into Integer objects when they are inserted into the list on line 7. The for loop beginning on line 11 uses an Iterator to step through the list elements and print their values to the console. On line 16 the TreeSet object is created and its elements are specified to be of type Integer. The set elements are populated with the unique elements contained in the list as was done in the previous version of this program. The for loop beginning on line 18 again uses an Iterator to step through the set elements. An enhanced for loop is used on line 23 to step through the set elements one last time. Figure 17-22 gives the results of running this example.

image from book
Figure 17-22: Results of Running Example 17.13

When To Use The Enhanced For Loop

You may rightly be wondering when is it appropriate to iterate over the elements of a collection using an enhanced for loop vs. an ordinary for loop and Iterator. An Iterator allows you to remove elements from a collection using the remove() method. If you simply want to step through a collection’s elements without modification then you can use the enhanced for loop. An enhanced for loop effectively hides the Iterator. If, however, you need to remove elements from the collection when you’re stepping through them then you must use an Iterator.

Static Polymorphism — Generic Methods

You can create generic methods with the help of Java 5 generics. A generic method is a method that can operate properly given different argument and/or return value types when the method is invoked.

Referring to example 17.14 — on line 5 the GenericTest class defines a static method named listArrayElements(). The <T> denotes a generic type placeholder. The T is then used in the method definition to declare an array parameter and to specify the type of element in the enhanced for loop on line 6. In the main() method beginning on line 12 an array of Integers is created and initialized with the help of the for loop on line 14. On line 19 the contents of int_array are printed to the console with the help of the listArrayElements() method. Next, on line 21, an array of Person references is created. Each element of person_array is initialized on lines 23 through 27 and the listArrayElements() method is used again on line 29 to print the contents of person_array to the console. The results of running this program are shown in figure 17-23.

Example 17.14: GenericTest.java

image from book
 1     import java.util.*; 2 3     public class GenericTest { 4 5       public static <T> void listArrayElements(T[] a){ 6          for(T o : a){ 7            System.out.println(o); 8          } 9          System.out.println(); 10      } 11 12      public static void main(String[] args){ 13        Integer[] int_array = new Integer[10]; 14        for(int i=0; i<int_array.length; i++){ 15          int_array[i] = i; 16        } 17 18 19        GenericTest.listArrayElements(int_array); 20 21        Person[] person_array = new Person[5]; 22 23        person_array[0] = new Person("Rick", "W", "Miller", 1966, 8, 28, Person.MALE); 24        person_array[1] = new Person("Steve", "J", "Jones", 1986, 2, 10, Person.MALE); 25        person_array[2] = new Person("Howard", "Josephus", "Stern", 1972, 5, 5, Person.MALE); 26        person_array[3] = new Person("Sally", "Sue", "Smith", 1987, 7, 2, Person.FEMALE); 27        person_array[4] = new Person("Karen", "H", "Stevens", 1977, 3, 18, Person.FEMALE); 28 29        GenericTest.listArrayElements(person_array); 30      }// end main() 31    }// end GenericTest class definition
image from book

image from book
Figure 17-23: Results of Running Example 17.14

Quick Review

The Java 5 platform introduced generics to the Java collections framework. Generic collections lets you specify element type in angle brackets.

Primitive type values will be autoboxed into their corresponding wrapper classes when being inserted into a generic collection. They will be unboxed when accessed.

The enhanced for loop hides the Iterator when you step through a collection’s elements. If you need to remove an element from a collection during iteration then you must use an ordinary for loop and Iterator combination.

Moving Forward

This section only provided a brief glimpse of the power and versatility of the Java 5 collections framework and Java generics. For more information on programming with generics please consult one of the excellent references on generics listed at the end of the chapter.




Java For Artists(c) The Art, Philosophy, and Science of Object-Oriented Programming
Java For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504052
EAN: 2147483647
Year: 2007
Pages: 452

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