org.snapscript.common.Vector Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of snap Show documentation
Show all versions of snap Show documentation
Dynamic scripting for the JVM
package org.snapscript.common;
import java.util.Iterator;
public class Vector implements Iterable {
private Node first;
private Node last;
private int size;
public Vector() {
super();
}
@Override
public Iterator iterator() {
return new NodeIterator(first);
}
public T first() {
if(first != null) {
return first.value;
}
return null;
}
public T last() {
if(last != null) {
return last.value;
}
return null;
}
public T get(int index) {
Node next = first;
for(int i = 0; i< index; i++) {
if(next == null) {
return null;
}
next = next.next;
}
return next.value;
}
public void add(T value) {
Node node = new Node(null, value);
if(first == null) {
first = node;
last =node;
} else {
last.next = node;
last = node;
}
size++;
}
public int size() {
return size;
}
private static class NodeIterator implements Iterator {
private Node next;
public NodeIterator(Node next) {
this.next = next;
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public T next() {
T value = null;
if(next != null) {
value = next.value;
next = next.next;
}
return value;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Remove not supported");
}
}
private static class Node {
private Node next;
private T value;
public Node(Node next, T value) {
this.value = value;
this.next = next;
}
}
}