View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.collections4.iterators;
18  
19  import java.util.List;
20  import java.util.ListIterator;
21  import java.util.Objects;
22  
23  import org.apache.commons.collections4.ResettableListIterator;
24  
25  /**
26   * Iterates backwards through a List, starting with the last element
27   * and continuing to the first. This is useful for looping around
28   * a list in reverse order without needing to actually reverse the list.
29   * <p>
30   * The first call to {@code next()} will return the last element
31   * from the list, and so on. The {@code hasNext()} method works
32   * in concert with the {@code next()} method as expected.
33   * However, the {@code nextIndex()} method returns the correct
34   * index in the list, thus it starts high and reduces as the iteration
35   * continues. The previous methods work similarly.
36   * </p>
37   *
38   * @param <E> The type of elements returned by this iterator.
39   * @since 3.2
40   */
41  public class ReverseListIterator<E> implements ResettableListIterator<E> {
42  
43      /** The list being wrapped. */
44      private final List<E> list;
45  
46      /** The list iterator being wrapped. */
47      private ListIterator<E> iterator;
48  
49      /** Flag to indicate if updating is possible at the moment. */
50      private boolean validForUpdate = true;
51  
52      /**
53       * Constructor that wraps a list.
54       *
55       * @param list  The list to create a reversed iterator for
56       * @throws NullPointerException if the list is null
57       */
58      public ReverseListIterator(final List<E> list) {
59          this.list = Objects.requireNonNull(list, "list");
60          iterator = list.listIterator(list.size());
61      }
62  
63      /**
64       * Adds a new element to the list between the next and previous elements.
65       *
66       * @param obj  The object to add
67       * @throws UnsupportedOperationException if the list is unmodifiable
68       * @throws IllegalStateException if the iterator is not in a valid state for set
69       */
70      @Override
71      public void add(final E obj) {
72          // the validForUpdate flag is needed as the necessary previous()
73          // method call re-enables remove and add
74          if (!validForUpdate) {
75              throw new IllegalStateException("Cannot add to list until next() or previous() called");
76          }
77          validForUpdate = false;
78          iterator.add(obj);
79          iterator.previous();
80      }
81  
82      /**
83       * Checks whether there is another element.
84       *
85       * @return true if there is another element
86       */
87      @Override
88      public boolean hasNext() {
89          return iterator.hasPrevious();
90      }
91  
92      /**
93       * Checks whether there is a previous element.
94       *
95       * @return true if there is a previous element
96       */
97      @Override
98      public boolean hasPrevious() {
99          return iterator.hasNext();
100     }
101 
102     /**
103      * Gets the next element.
104      * The next element is the previous in the list.
105      *
106      * @return The next element in the iterator
107      */
108     @Override
109     public E next() {
110         final E obj = iterator.previous();
111         validForUpdate = true;
112         return obj;
113     }
114 
115     /**
116      * Gets the index of the next element.
117      *
118      * @return The index of the next element in the iterator
119      */
120     @Override
121     public int nextIndex() {
122         return iterator.previousIndex();
123     }
124 
125     /**
126      * Gets the previous element.
127      * The next element is the previous in the list.
128      *
129      * @return The previous element in the iterator
130      */
131     @Override
132     public E previous() {
133         final E obj = iterator.next();
134         validForUpdate = true;
135         return obj;
136     }
137 
138     /**
139      * Gets the index of the previous element.
140      *
141      * @return The index of the previous element in the iterator
142      */
143     @Override
144     public int previousIndex() {
145         return iterator.nextIndex();
146     }
147 
148     /**
149      * Removes the last returned element.
150      *
151      * @throws UnsupportedOperationException if the list is unmodifiable
152      * @throws IllegalStateException if there is no element to remove
153      */
154     @Override
155     public void remove() {
156         if (!validForUpdate) {
157             throw new IllegalStateException("Cannot remove from list until next() or previous() called");
158         }
159         iterator.remove();
160     }
161 
162     /**
163      * Resets the iterator back to the start (which is the
164      * end of the list as this is a reversed iterator)
165      */
166     @Override
167     public void reset() {
168         iterator = list.listIterator(list.size());
169     }
170 
171     /**
172      * Replaces the last returned element.
173      *
174      * @param obj  The object to set
175      * @throws UnsupportedOperationException if the list is unmodifiable
176      * @throws IllegalStateException if the iterator is not in a valid state for set
177      */
178     @Override
179     public void set(final E obj) {
180         if (!validForUpdate) {
181             throw new IllegalStateException("Cannot set to list until next() or previous() called");
182         }
183         iterator.set(obj);
184     }
185 
186 }