
com.github.sirikid.iterators.SingletonIterator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of maybe Show documentation
Show all versions of maybe Show documentation
Implementation Maybe monad in Java
The newest version!
/*
* Copyright (c) 2015-2016, Ivan Sokolov. All rights reserved.
* This code is licensed under MIT license (see LICENSE for details)
*/
package com.github.sirikid.iterators;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import javax.annotation.Nullable;
/**
* Iterator, that contains only one element.
*
* @author Ivan Sokolov
* @version 1.1.0
* @param type of element
* @see SingletonSpliterator
* @since 1.0.0
*/
public class SingletonIterator implements ListIterator {
@Nullable private final T value;
private boolean alreadyUsed;
/**
* Sole constructor.
*
* @param value the value to be in iterator
*/
public SingletonIterator(@Nullable T value) {
this.value = value;
alreadyUsed = false;
}
@Override
public boolean hasNext() {
return !alreadyUsed;
}
@Override
public T next() {
if (!hasNext()) throw new NoSuchElementException();
alreadyUsed = true;
return value;
}
@Override
public boolean hasPrevious() {
return alreadyUsed;
}
@Override
public T previous() {
if (!hasPrevious()) throw new NoSuchElementException();
alreadyUsed = false;
return value;
}
@Override
public int nextIndex() {
return alreadyUsed ? 1 : 0;
}
@Override
public int previousIndex() {
return alreadyUsed ? 0 : -1;
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove");
}
@Override
public void set(final T unused) {
throw new UnsupportedOperationException("set");
}
@Override
public void add(final T unused) {
throw new UnsupportedOperationException("add");
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy