All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.snapscript.common.Vector Maven / Gradle / Ivy

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;
      }
   }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy