Java Reference
In-Depth Information
Viewing Arrays as List s and Converting List s to Arrays
Figure 16.4 uses Arrays method asList to view an array as a List and uses List method
toArray to get an array from a LinkedList collection. The program calls method asList
to create a List view of an array, which is used to initialize a LinkedList object, then adds
a series of String s to the LinkedList and calls method toArray to obtain an array con-
taining references to the String s.
1
// Fig. 16.4: UsingToArray.java
2
// Viewing arrays as Lists and converting Lists to arrays.
3
import java.util.LinkedList;
4
import java.util.Arrays;
5
6
public class UsingToArray
7
{
8
// creates a LinkedList, adds elements and converts to array
9
public static void main(String[] args)
10
{
11
String[] colors = { "black" , "blue" , "yellow" };
12
LinkedList<String> links = new LinkedList<>(Arrays.asList(colors));
13
14
links.addLast( "red" ); // add as last item
links.add( "pink" ); // add to the end
links.add( 3 , "green" ); // add at 3rd index
links.addFirst( "cyan" ); // add as first item
15
16
17
18
19
// get LinkedList elements as an array
colors = links.toArray( new String[links.size()]);
20
21
22
System.out.println( "colors: " );
23
24
for (String color : colors)
25
System.out.println(color);
26
}
27
} // end class UsingToArray
colors:
cyan
black
blue
yellow
green
red
pink
Fig. 16.4 | Viewing arrays as List s and converting List s to arrays.
Line 12 constructs a LinkedList of String s containing the elements of array colors .
Arrays method asList returns a List view of the array, then uses that to initialize the
LinkedList with its constructor that receives a Collection as an argument (a List is a
Collection ). Line 14 calls LinkedList method addLast to add "red" to the end of links .
Lines 15-16 call LinkedList method add to add "pink" as the last element and "green"
as the element at index 3 (i.e., the fourth element). Method addLast (line 14) functions
 
Search WWH ::




Custom Search