The List Interface In Java


SUBMITTED BY: Guest

DATE: Dec. 5, 2013, 5:19 p.m.

FORMAT: Text only

SIZE: 17.4 kB

HITS: 865

  1. The List Interface
  2. Beta Draft 2013-10-15
  3. This section was updated to reflect features and conventions of the upcoming Java SE 8 release. You can download the current JDK 8 snapshot from java.net.
  4. A List is an ordered Collection (sometimes called a sequence). Lists may contain duplicate elements. In addition to the operations inherited from Collection, the List interface includes operations for the following:
  5. Positional access — manipulates elements based on their numerical position in the list. This includes methods such as get, set, add, addAll, and remove.
  6. Search — searches for a specified object in the list and returns its numerical position. Search methods include indexOf and lastIndexOf.
  7. Iteration — extends Iterator semantics to take advantage of the list's sequential nature. The listIterator methods provide this behavior.
  8. Range-view — The sublist method performs arbitrary range operations on the list.
  9. The Java platform contains two general-purpose List implementations. ArrayList, which is usually the better-performing implementation, and LinkedList which offers better performance under certain circumstances.
  10. Collection Operations
  11. The operations inherited from Collection all do about what you'd expect them to do, assuming you're already familiar with them. If you're not familiar with them from Collection, now would be a good time to read The Collection Interface section. The remove operation always removes the first occurrence of the specified element from the list. The add and addAll operations always append the new element(s) to the end of the list. Thus, the following idiom concatenates one list to another.
  12. list1.addAll(list2);
  13. Here's a nondestructive form of this idiom, which produces a third List consisting of the second list appended to the first.
  14. List<Type> list3 = new ArrayList<Type>(list1);
  15. list3.addAll(list2);
  16. Note that the idiom, in its nondestructive form, takes advantage of ArrayList's standard conversion constructor.
  17. And here's an example (JDK 8 and later) that aggregates some names into a List:
  18. List<String> list = people.stream()
  19. .map(Person::getName)
  20. .collect(Collectors.toList());
  21. Like the Set interface, List strengthens the requirements on the equals and hashCode methods so that two List objects can be compared for logical equality without regard to their implementation classes. Two List objects are equal if they contain the same elements in the same order.
  22. Positional Access and Search Operations
  23. The basic positional access operations are get, set, add and remove. (The set and remove operations return the old value that is being overwritten or removed.) Other operations (indexOf and lastIndexOf) return the first or last index of the specified element in the list.
  24. The addAll operation inserts all the elements of the specified Collection starting at the specified position. The elements are inserted in the order they are returned by the specified Collection's iterator. This call is the positional access analog of Collection's addAll operation.
  25. Here's a little method to swap two indexed values in a List.
  26. public static <E> void swap(List<E> a, int i, int j) {
  27. E tmp = a.get(i);
  28. a.set(i, a.get(j));
  29. a.set(j, tmp);
  30. }
  31. Of course, there's one big difference. This is a polymorphic algorithm: It swaps two elements in any List, regardless of its implementation type. Here's another polymorphic algorithm that uses the preceding swap method.
  32. public static void shuffle(List<?> list, Random rnd) {
  33. for (int i = list.size(); i > 1; i--)
  34. swap(list, i - 1, rnd.nextInt(i));
  35. }
  36. This algorithm, which is included in the Java platform's Collections class, randomly permutes the specified list using the specified source of randomness. It's a bit subtle: It runs up the list from the bottom, repeatedly swapping a randomly selected element into the current position. Unlike most naive attempts at shuffling, it's fair (all permutations occur with equal likelihood, assuming an unbiased source of randomness) and fast (requiring exactly list.size()-1 swaps). The following program uses this algorithm to print the words in its argument list in random order.
  37. import java.util.*;
  38. public class Shuffle {
  39. public static void main(String[] args) {
  40. List<String> list = new ArrayList<String>();
  41. for (String a : args)
  42. list.add(a);
  43. Collections.shuffle(list, new Random());
  44. System.out.println(list);
  45. }
  46. }
  47. In fact, this program can be made even shorter and faster. The Arrays class has a static factory method called asList, which allows an array to be viewed as a List. This method does not copy the array. Changes in the List write through to the array and vice versa. The resulting List is not a general-purpose List implementation, because it doesn't implement the (optional) add and remove operations: Arrays are not resizable. Taking advantage of Arrays.asList and calling the library version of shuffle, which uses a default source of randomness, you get the following tiny program whose behavior is identical to the previous program.
  48. import java.util.*;
  49. public class Shuffle {
  50. public static void main(String[] args) {
  51. List<String> list = Arrays.asList(args);
  52. Collections.shuffle(list);
  53. System.out.println(list);
  54. }
  55. }
  56. Iterators
  57. As you'd expect, the Iterator returned by List's iterator operation returns the elements of the list in proper sequence. List also provides a richer iterator, called a ListIterator, which allows you to traverse the list in either direction, modify the list during iteration, and obtain the current position of the iterator.
  58. The three methods that ListIterator inherits from Iterator (hasNext, next, and remove) do exactly the same thing in both interfaces. The hasPrevious and the previous operations are exact analogues of hasNext and next. The former operations refer to the element before the (implicit) cursor, whereas the latter refer to the element after the cursor. The previous operation moves the cursor backward, whereas next moves it forward.
  59. Here's the standard idiom for iterating backward through a list.
  60. for (ListIterator<Type> it = list.listIterator(list.size()); it.hasPrevious(); ) {
  61. Type t = it.previous();
  62. ...
  63. }
  64. Note the argument to listIterator in the preceding idiom. The List interface has two forms of the listIterator method. The form with no arguments returns a ListIterator positioned at the beginning of the list; the form with an int argument returns a ListIterator positioned at the specified index. The index refers to the element that would be returned by an initial call to next. An initial call to previous would return the element whose index was index-1. In a list of length n, there are n+1 valid values for index, from 0 to n, inclusive.
  65. Intuitively speaking, the cursor is always between two elements — the one that would be returned by a call to previous and the one that would be returned by a call to next. The n+1 valid index values correspond to the n+1 gaps between elements, from the gap before the first element to the gap after the last one. The following figure shows the five possible cursor positions in a list containing four elements.
  66. Five arrows representing five cursor positions, from 0 to 4, with four elements, one between each arrow.
  67. The five possible cursor positions.
  68. Calls to next and previous can be intermixed, but you have to be a bit careful. The first call to previous returns the same element as the last call to next. Similarly, the first call to next after a sequence of calls to previous returns the same element as the last call to previous.
  69. It should come as no surprise that the nextIndex method returns the index of the element that would be returned by a subsequent call to next, and previousIndex returns the index of the element that would be returned by a subsequent call to previous. These calls are typically used either to report the position where something was found or to record the position of the ListIterator so that another ListIterator with identical position can be created.
  70. It should also come as no surprise that the number returned by nextIndex is always one greater than the number returned by previousIndex. This implies the behavior of the two boundary cases: (1) a call to previousIndex when the cursor is before the initial element returns -1 and (2) a call to nextIndex when the cursor is after the final element returns list.size(). To make all this concrete, the following is a possible implementation of List.indexOf.
  71. public int indexOf(E e) {
  72. for (ListIterator<E> it = listIterator(); it.hasNext(); )
  73. if (e == null ? it.next() == null : e.equals(it.next()))
  74. return it.previousIndex();
  75. // Element not found
  76. return -1;
  77. }
  78. Note that the indexOf method returns it.previousIndex() even though it is traversing the list in the forward direction. The reason is that it.nextIndex() would return the index of the element we are about to examine, and we want to return the index of the element we just examined.
  79. The Iterator interface provides the remove operation to remove the last element returned by next from the Collection. For ListIterator, this operation removes the last element returned by next or previous. The ListIterator interface provides two additional operations to modify the list — set and add. The set method overwrites the last element returned by next or previous with the specified element. The following polymorphic algorithm uses set to replace all occurrences of one specified value with another.
  80. public static <E> void replace(List<E> list, E val, E newVal) {
  81. for (ListIterator<E> it = list.listIterator(); it.hasNext(); )
  82. if (val == null ? it.next() == null : val.equals(it.next()))
  83. it.set(newVal);
  84. }
  85. The only bit of trickiness in this example is the equality test between val and it.next. You need to special-case a val value of null to prevent a NullPointerException.
  86. The add method inserts a new element into the list immediately before the current cursor position. This method is illustrated in the following polymorphic algorithm to replace all occurrences of a specified value with the sequence of values contained in the specified list.
  87. public static <E>
  88. void replace(List<E> list, E val, List<? extends E> newVals) {
  89. for (ListIterator<E> it = list.listIterator(); it.hasNext(); ){
  90. if (val == null ? it.next() == null : val.equals(it.next())) {
  91. it.remove();
  92. for (E e : newVals)
  93. it.add(e);
  94. }
  95. }
  96. }
  97. Range-View Operation
  98. The range-view operation, subList(int fromIndex, int toIndex), returns a List view of the portion of this list whose indices range from fromIndex, inclusive, to toIndex, exclusive. This half-open range mirrors the typical for loop.
  99. for (int i = fromIndex; i < toIndex; i++) {
  100. ...
  101. }
  102. As the term view implies, the returned List is backed up by the List on which subList was called, so changes in the former are reflected in the latter.
  103. This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a List can be used as a range operation by passing a subList view instead of a whole List. For example, the following idiom removes a range of elements from a List.
  104. list.subList(fromIndex, toIndex).clear();
  105. Similar idioms can be constructed to search for an element in a range.
  106. int i = list.subList(fromIndex, toIndex).indexOf(o);
  107. int j = list.subList(fromIndex, toIndex).lastIndexOf(o);
  108. Note that the preceding idioms return the index of the found element in the subList, not the index in the backing List.
  109. Any polymorphic algorithm that operates on a List, such as the replace and shuffle examples, works with the List returned by subList.
  110. Here's a polymorphic algorithm whose implementation uses subList to deal a hand from a deck. That is, it returns a new List (the "hand") containing the specified number of elements taken from the end of the specified List (the "deck"). The elements returned in the hand are removed from the deck.
  111. public static <E> List<E> dealHand(List<E> deck, int n) {
  112. int deckSize = deck.size();
  113. List<E> handView = deck.subList(deckSize - n, deckSize);
  114. List<E> hand = new ArrayList<E>(handView);
  115. handView.clear();
  116. return hand;
  117. }
  118. Note that this algorithm removes the hand from the end of the deck. For many common List implementations, such as ArrayList, the performance of removing elements from the end of the list is substantially better than that of removing elements from the beginning.
  119. The following is a program that uses the dealHand method in combination with Collections.shuffle to generate hands from a normal 52-card deck. The program takes two command-line arguments: (1) the number of hands to deal and (2) the number of cards in each hand.
  120. import java.util.*;
  121. public class Deal {
  122. public static void main(String[] args) {
  123. if (args.length < 2) {
  124. System.out.println("Usage: Deal hands cards");
  125. return;
  126. }
  127. int numHands = Integer.parseInt(args[0]);
  128. int cardsPerHand = Integer.parseInt(args[1]);
  129. // Make a normal 52-card deck.
  130. String[] suit = new String[] {
  131. "spades", "hearts",
  132. "diamonds", "clubs"
  133. };
  134. String[] rank = new String[] {
  135. "ace", "2", "3", "4",
  136. "5", "6", "7", "8", "9", "10",
  137. "jack", "queen", "king"
  138. };
  139. List<String> deck = new ArrayList<String>();
  140. for (int i = 0; i < suit.length; i++)
  141. for (int j = 0; j < rank.length; j++)
  142. deck.add(rank[j] + " of " + suit[i]);
  143. // Shuffle the deck.
  144. Collections.shuffle(deck);
  145. if (numHands * cardsPerHand > deck.size()) {
  146. System.out.println("Not enough cards.");
  147. return;
  148. }
  149. for (int i = 0; i < numHands; i++)
  150. System.out.println(dealHand(deck, cardsPerHand));
  151. }
  152. public static <E> List<E> dealHand(List<E> deck, int n) {
  153. int deckSize = deck.size();
  154. List<E> handView = deck.subList(deckSize - n, deckSize);
  155. List<E> hand = new ArrayList<E>(handView);
  156. handView.clear();
  157. return hand;
  158. }
  159. }
  160. Running the program produces output like the following.
  161. % java Deal 4 5
  162. [8 of hearts, jack of spades, 3 of spades, 4 of spades,
  163. king of diamonds]
  164. [4 of diamonds, ace of clubs, 6 of clubs, jack of hearts,
  165. queen of hearts]
  166. [7 of spades, 5 of spades, 2 of diamonds, queen of diamonds,
  167. 9 of clubs]
  168. [8 of spades, 6 of diamonds, ace of spades, 3 of hearts,
  169. ace of hearts]
  170. Although the subList operation is extremely powerful, some care must be exercised when using it. The semantics of the List returned by subList become undefined if elements are added to or removed from the backing List in any way other than via the returned List. Thus, it's highly recommended that you use the List returned by subList only as a transient object — to perform one or a sequence of range operations on the backing List. The longer you use the subList instance, the greater the probability that you'll compromise it by modifying the backing List directly or through another subList object. Note that it is legal to modify a sublist of a sublist and to continue using the original sublist (though not concurrently).
  171. List Algorithms
  172. Most polymorphic algorithms in the Collections class apply specifically to List. Having all these algorithms at your disposal makes it very easy to manipulate lists. Here's a summary of these algorithms, which are described in more detail in the Algorithms section.
  173. sort — sorts a List using a merge sort algorithm, which provides a fast, stable sort. (A stable sort is one that does not reorder equal elements.)
  174. shuffle — randomly permutes the elements in a List.
  175. reverse — reverses the order of the elements in a List.
  176. rotate — rotates all the elements in a List by a specified distance.
  177. swap — swaps the elements at specified positions in a List.
  178. replaceAll — replaces all occurrences of one specified value with another.
  179. fill — overwrites every element in a List with the specified value.
  180. copy — copies the source List into the destination List.
  181. binarySearch — searches for an element in an ordered List using the binary search algorithm.
  182. indexOfSubList — returns the index of the first sublist of one List that is equal to another.
  183. lastIndexOfSubList — returns the index of the last sublist of one List that is equal to another.

comments powered by Disqus