Java Reference
In-Depth Information
l . set ( 0 , last ); // The last shall be first
// Adding and inserting elements. add can append or insert
l . add ( first ); // Append the first word at end of list
l . add ( 0 , first ); // Insert first at the start of the list again
l . addAll ( words ); // Append a collection at the end of the list
l . addAll ( 1 , words ); // Insert collection after first word
// Sublists: backed by the original list
List < String > sub = l . subList ( 1 , 3 ); // second and third elements
sub . set ( 0 , "hi" ); // modifies 2nd element of l
// Sublists can restrict operations to a subrange of backing list
String s = Collections . min ( l . subList ( 0 , 4 ));
Collections . sort ( l . subList ( 0 , 4 ));
// Independent copies of a sublist don't affect the parent list.
List < String > subcopy = new ArrayList < String >( l . subList ( 1 , 3 ));
// Searching lists
int p = l . indexOf ( last ); // Where does the last word appear?
p = l . lastIndexOf ( last ); // Search backward
// Print the index of all occurrences of last in l. Note subList
int n = l . size ();
p = 0 ;
do {
// Get a view of the list that includes only the elements we
// haven't searched yet.
List < String > list = l . subList ( p , n );
int q = list . indexOf ( last );
if ( q == - 1 ) break ;
System . out . printf ( "Found '%s' at index %d%n" , last , p + q );
p += q + 1 ;
} while ( p < n );
// Removing elements from a list
l . remove ( last ); // Remove first occurrence of the element
l . remove ( 0 ); // Remove element at specified index
l . subList ( 0 , 2 ). clear (); // Remove a range of elements using subList
l . retainAll ( words ); // Remove all but elements in words
l . removeAll ( words ); // Remove all occurrences of elements in words
l . clear (); // Remove everything
Foreach loops and iteration
One very important way of working with collections is to process each element in
turn, an approach known as iteration. This is an older way of looking at data strucā€
tures, but is still very useful (especially for small collections of data) and is easy to
understand. This approach fits naturally with the for loop, as shown in this bit of
code, and is easiest to illustrate using a List :
s
a
ListCollection < String > c = new ArrayList < String >();
// ... add some Strings to c
 
Search WWH ::




Custom Search