Subato

Iterator einfach verkettete Liste

package name.panitz.util;
import java.util.Iterator;

public class LL<A> implements Iterable<A> {
  private final A hd;
  private final LL<A> tl;

  public boolean isEmpty() {
    return hd == null && tl == null;
  }

  public LL(A hd, LL<A> tl) {
    this.hd = hd;
    this.tl = tl;
  }

  public LL() {
    this(null, null);
  }

  public A get(int i) {
    return i == 0 ? hd : tl.get(i - 1);
  }

  public int size() {
    if (isEmpty())
      return 0;
    return 1 + tl.size();
  }

  @Override
  public Iterator<A> iterator(){
    return new Iterator<A>(){
      LL<A> xs = LL.this;
      @Override public boolean hasNext(){
        return !xs.isEmpty();
      }
      @Override public A next(){
        var result = xs.hd;
        xs = xs.tl;
        return result;
      }
    };
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((hd == null) ? 0 : hd.hashCode());
    result = prime * result + ((tl == null) ? 0 : tl.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (!(obj instanceof LL)){
      return false;
    }
    LL other = (LL) obj;
    if (hd == null) {
      if (other.hd != null) {
        return false;
      }
    } else if (!hd.equals(other.hd)) {
      return false;
    }
    if (tl == null) {
      if (other.tl != null) {
        return false;
      }
    } else if (!tl.equals(other.tl)) {
      return false;
    }
    return true;
  }

  @SuppressWarnings("unchecked")
  static <A> LL<A> create(A... es){
    LL<A> result = new LL<A>();
    for (int i=es.length-1;i>=0;i--){
      result = new LL<A>(es[i],result);
    }
    return result;  
  }

  @Override 
  public String toString(){
    StringBuffer result = new StringBuffer("[");
    boolean first = true;
    for (LL<A> it = this;!it.isEmpty();it=it.tl){
      if (first){
        first = false;
      } else{
        result.append(", ");
      }
      result.append(it.hd);
    }
    result.append("]");
    return result.toString();
  }
}