Java Reference
In-Depth Information
nized collections provide better performance than synchronized ones. For this reason, Array-
List is typically preferred over Vector in programs that do not share a collection among
threads. Separately, the Java collections API provides synchronization wrappers
(Section 16.13) that can be used to add synchronization to the unsynchronized collections,
and several powerful synchronized collections are available in the Java concurrency APIs.
Performance Tip 16.1
ArrayList s behave like Vector s without synchronization and therefore execute faster
than Vectors , because ArrayList s do not have the overhead of thread synchronization.
Software Engineering Observation 16.3
LinkedList s can be used to create stacks, queues and deques (double-ended queues,
pronounced “decks”). The collections framework provides implementations of some of
these data structures.
The following three subsections demonstrate the List and Collection capabilities.
Section 16.6.1 removes elements from an ArrayList with an Iterator . Section 16.6.2
uses ListIterator and several List - and LinkedList -specific methods.
16.6.1 ArrayList and Iterator
Figure 16.2 uses an ArrayList (introduced in Section 7.16) to demonstrate several capa-
bilities of interface Collection . The program places two Color arrays in ArrayList s and
uses an Iterator to remove elements in the second ArrayList collection from the first.
1
// Fig. 16.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
Fig. 16.2 | Collection interface demonstrated via an ArrayList object. (Part 1 of 2.)
 
 
Search WWH ::




Custom Search