Subato

Array-basierte Liste

package name.panitz.util;
import java.util.Comparator;
import java.util.function.Consumer;
import java.util.function.Predicate;

public class AL<E> implements List<E> {
  protected E[] store = (E[]) new Object[5];
  protected int size = 0;

  public AL(E... es) {
    for (E e : es)
      add(e);
  }

  private void mkNewStore() {
    E[] newStore = (E[]) new Object[size + 5];
    for (int i = 0; i < store.length; i++)
      newStore[i] = store[i];
    store = newStore;
  }

  public void add(E e) {
    if (store.length <= size)
      mkNewStore();
    store[size++] = e;
  }

  public boolean contains(E e) {
    return containsWith((x) -> x.equals(e));
  }

  public int size() {
    return size;
  }

  public E get(int i) {
    return store[i];
  }

  public void remove(int i) {
    if (i < 0 || i >= size())
      return;
    for (int j = i; j < store.length - 1; j++) {
      store[j] = store[j + 1];
    }
    size--;
  }

  public void addAll(List<E> cs) {
    cs.forEach(c -> add(c));
  }

  public boolean containsWith(Predicate<E> pred) {
    for (int i = 0; i < size(); i++) {
      if (pred.test(get(i)))
        return true;
    }
    return false;
  }

  public AL<E> sublist(int i, int l) {
    AL<E> result = new AL<>();
    for (int k = i; k < i + l && k < size(); k++) {
      result.add(get(k));
    }
    return result;
  }

  @Override
  public boolean startsWith(List<E> that) {
    if (that.size() > size)
      return false;
    for (int i = 0; i < that.size(); i++) {
      if (!get(i).equals(that.get(i)))
        return false;
    }
    return true;
  }

  @Override
  public boolean endsWith(List<E> that) {
    if (that.size() > size)
      return false;
    for (int i = 0; i < that.size(); i++) {
      if (!get(i + this.size-that.size()).equals(that.get(i)))
        return false;
    }
    return true;
  }

  @Override
  public void reverse() {
    for (int i = 0; i < size() / 2; i++) {
      E tmp = store[i];
      store[i] = store[size() - i - 1];
      store[size() - i - 1] = tmp;
    }
  }

  @Override
  public void insert(int i, E e) {
    if (i<0) return;
    if (i >= size()) {
      add(e);
      return;
    } else if (i < size()) {
      if (size() == store.length)
        mkNewStore();
      for (int j = size(); j > i; j--) {
        store[j] = store[j - 1];
      }
      store[i] = e;
      size++;
    }
  }

  @Override
  public void forEach(Consumer<? super E> consumer) {
    for (int i = 0; i < size(); i++) {
      consumer.accept(get(i));
    }
  }

  public void sortBy(Comparator<? super E> cmp) {
    for (int i = size(); i > 0; i--) {
      for (int j = 0; j < i - 1; j++) {
        if (cmp.compare(store[j], store[j + 1]) > 0) {
          E tmp = store[j];
          store[j] = store[j + 1];
          store[j + 1] = tmp;
        }
      }
    }
  }
}