001 /*
002 * Java Genetic Algorithm Library (jenetics-3.5.0).
003 * Copyright (c) 2007-2016 Franz Wilhelmstötter
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 *
017 * Author:
018 * Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
019 */
020 package org.jenetics.internal.collection;
021
022 import static java.util.Objects.requireNonNull;
023
024 import java.util.ListIterator;
025 import java.util.NoSuchElementException;
026
027 /**
028 * @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
029 * @since 1.4
030 * @version 3.4
031 */
032 public class ArrayIterator<T> implements ListIterator<T> {
033
034 public final Array<T> array;
035
036 protected int cursor = 0;
037 protected int lastElement = -1;
038
039 public ArrayIterator(final Array<T> array) {
040 this.array = requireNonNull(array, "Array must not be null.");
041 }
042
043 @Override
044 public boolean hasNext() {
045 return cursor != array.length();
046 }
047
048 @Override
049 public T next() {
050 final int i = cursor;
051 if (cursor >= array.length()) {
052 throw new NoSuchElementException();
053 }
054
055 cursor = i + 1;
056 return array.get(lastElement = i);
057 }
058
059 @Override
060 public int nextIndex() {
061 return cursor;
062 }
063
064 @Override
065 public boolean hasPrevious() {
066 return cursor != 0;
067 }
068
069 @Override
070 public T previous() {
071 final int i = cursor - 1;
072 if (i < 0) {
073 throw new NoSuchElementException();
074 }
075
076 cursor = i;
077 return array.get(lastElement = i);
078 }
079
080 @Override
081 public int previousIndex() {
082 return cursor - 1;
083 }
084
085 @Override
086 public void set(final T value) {
087 throw new UnsupportedOperationException(
088 "Iterator is immutable."
089 );
090 }
091
092 @Override
093 public void add(final T value) {
094 throw new UnsupportedOperationException(
095 "Can't change Iterator size."
096 );
097 }
098
099 @Override
100 public void remove() {
101 throw new UnsupportedOperationException(
102 "Can't change Iterator size."
103 );
104 }
105
106 }
|