Last active
December 31, 2015 22:19
-
-
Save dha-lo-jd/8052601 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Iterator; | |
import java.util.List; | |
import java.util.NoSuchElementException; | |
import lombok.AllArgsConstructor; | |
import lombok.Data; | |
import com.google.common.collect.Lists; | |
@AllArgsConstructor(staticName = "of") | |
public class LinkedLoop<T> implements Iterable<LinkedLoop.Link<T>> { | |
@Data | |
@AllArgsConstructor | |
public static class Link<T> { | |
private final T previous; | |
private final T next; | |
private final T value; | |
public Link() { | |
this(null, null, null); | |
} | |
public boolean isFirst() { | |
return previous == null; | |
} | |
public boolean isLast() { | |
return next == null; | |
} | |
public Link<T> push(T next) { | |
Link<T> link = new Link<T>(value, next, this.next); | |
return link; | |
} | |
} | |
public static class LinkedLoopIterator<T> implements Iterator<Link<T>> { | |
private final Iterator<T> src; | |
private Link<T> current; | |
private boolean last; | |
protected LinkedLoopIterator(Iterator<T> src) { | |
this.src = src; | |
current = new Link<>(); | |
if (src.hasNext()) { | |
current = current.push(src.next()); | |
} | |
} | |
@Override | |
public boolean hasNext() { | |
return !last; | |
} | |
@Override | |
public Link<T> next() { | |
if (!last) { | |
last = !src.hasNext(); | |
T next = null; | |
if (!last) { | |
next = src.next(); | |
} | |
current = current.push(next); | |
return current; | |
} else { | |
throw new NoSuchElementException(); | |
} | |
} | |
@Override | |
public void remove() { | |
throw new UnsupportedOperationException(); | |
} | |
} | |
public static void main(String[] args) { | |
List<String> list = Lists.newArrayList("hoge", "fuga", "foo", "bar"); | |
for (Link<String> link : LinkedLoop.of(list)) { | |
Object[] a = { | |
link.getPrevious(), link.getValue(), link.getNext(), link.isFirst(), link.isLast(), | |
}; | |
System.out.println(String.format("previous: %s, value: %s, next: %s. isFirst: %b, isLast: %b", a)); | |
} | |
} | |
private final Iterable<T> src; | |
@Override | |
public Iterator<Link<T>> iterator() { | |
return new LinkedLoopIterator(src.iterator()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment