• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.timezone.location.storage.tzs2range.write;
18 
19 import java.util.ArrayList;
20 import java.util.Iterator;
21 
22 /**
23  * An iterator that can have elements pushed back onto it. {@link #remove()} is not supported.
24  *
25  * @param <E> The type of the element returned by this iterator
26  */
27 public final class PushBackIterator<E> implements Iterator<E> {
28 
29     private final ArrayList<E> mPushBackStack = new ArrayList<>();
30 
31     private final Iterator<E> mIterator;
32 
PushBackIterator(Iterator<E> iterator)33     public PushBackIterator(Iterator<E> iterator) {
34         mIterator = iterator;
35     }
36 
37     @Override
hasNext()38     public boolean hasNext() {
39         return !mPushBackStack.isEmpty() || mIterator.hasNext();
40     }
41 
42     @Override
next()43     public E next() {
44         if (!mPushBackStack.isEmpty()) {
45             return mPushBackStack.remove(mPushBackStack.size() - 1);
46         }
47         return mIterator.next();
48     }
49 
50     /**
51      * Pushes the element to the front of the iterator again.
52      */
pushBack(E element)53     public void pushBack(E element) {
54         mPushBackStack.add(element);
55     }
56 }
57