THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

There are numerous methods for working with lists:


public static <T> booleanreplaceAll(List<T> list, T oldVal, T
newVal)

Replaces all occurrences of oldVal in the list with newVal. Returns true
if any replacements were made.

public static voidreverse(List<?> list)

Reverses the order of the elements of the list.

public static voidrotate(List<?> list, int distance)

Rotates all of the elements in the list by the specified distance. A positive
distance moves elements toward the end of the list, wrapping around to the
beginning. A negative distance moves elements toward the head of the list,
wrapping around to the end. For example, given a list v, w, x, y, z, a rotate
with distance 1 will change the list to be z, v, w, x, y (as will a rotation of 6,
11, ... or 4, 9, ...).

public static voidshuffle(List<?> list)

Randomly shuffles the list.

public static voidshuffle(List<?> list, Random randomSource)

Randomly shuffles the list using randomSource as the source of random
numbers (see "Random" on page 639).

public static voidswap(List<?> list, int i, int j)

Swaps the ith and jth elements of the given list. This can be done efficiently
inside the collection.

public static <T> voidfill(List<? super T> list, T elem)

Replaces each element of list with elem.

public static <T> voidcopy(List<? super T> dest, List<?
extends T> src)

Copies each element to dst from src. If dst is too small to contain all the
elements, throws IndexOutOfBoundsException. You can use a sublist
for either dst or src to copy only to or from parts of a list.

public static <T> List<T>nCopies(int n, T elem)

Returns an immutable list that contains n elements, each of which is elem.
This only requires storing one reference to elem, so n can be 100 and the
returned list will take the same amount of space it would if n were one.

public static intindexOfSubList(List<?> source, List<?>
target)
Free download pdf