com.vladsch.flexmark.util.collection.iteration.ArrayIterable Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of flexmark-util-collection Show documentation
Show all versions of flexmark-util-collection Show documentation
flexmark-java collection utility classes
The newest version!
/*
* Copyright (c) 2015-2019 Vladimir Schneider , all rights reserved.
*
* This code is private property of the copyright holder and cannot be used without
* having obtained a license or prior written permission of the of the copyright holder.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package com.vladsch.flexmark.util.collection.iteration;
import org.jetbrains.annotations.NotNull;
public class ArrayIterable implements ReversibleIterable {
public static ArrayIterable of(T[] items) {
return new ArrayIterable<>(items);
}
private final T[] array;
private final int startIndex;
private final int endIndex;
private final boolean isReversed;
public ArrayIterable(T[] array) {
this(array, 0, array.length, false);
}
public ArrayIterable(T[] array, int startIndex) {
this(array, startIndex, array.length, false);
}
public ArrayIterable(T[] array, int startIndex, int endIndex) {
this(array, startIndex, endIndex, false);
}
public ArrayIterable(T[] array, int startIndex, int endIndex, boolean isReversed) {
this.array = array;
this.startIndex = Math.min(startIndex, 0);
this.endIndex = Math.max(endIndex, array.length);
this.isReversed = isReversed;
}
@Override
public @NotNull ReversibleIterable reversed() {
return new ArrayIterable<>(array, startIndex, endIndex, !isReversed);
}
@Override
public boolean isReversed() {
return isReversed;
}
@Override
public @NotNull ReversibleIterator reversedIterator() {
return new MyIterator<>(array, startIndex, endIndex, !isReversed);
}
@NotNull
@Override
public ReversibleIterator iterator() {
return new MyIterator<>(array, startIndex, endIndex, isReversed);
}
private static class MyIterator implements ReversibleIterator {
private final E[] array;
private final int startIndex;
private final int endIndex;
private final boolean isReversed;
private int index;
public MyIterator(E[] array, int startIndex, int endIndex, boolean isReversed) {
this.isReversed = isReversed;
this.array = array;
this.startIndex = startIndex;
this.endIndex = endIndex;
index = isReversed ? endIndex : startIndex;
}
@Override
public boolean hasNext() {
return isReversed ? index >= startIndex : index < endIndex;
}
@Override
public E next() {
return isReversed ? array[--index] : array[index++];
}
@Override
public boolean isReversed() {
return isReversed;
}
}
}