package jist.swans.misc;

import java.util.Collection;
import java.util.Comparator;
import java.util.LinkedList;

/**
A simple priority list, also called a priority queue.
Objects in the list are ordered by their priority,
determined by the object's Comparable interface.
The highest priority item is first in the list.
*/
public class PriorityList extends LinkedList {

  private static final long serialVersionUID = -4751049056047615550L;

  private Comparator comparator;

  public PriorityList() {
    super();
  }

  public PriorityList(Collection c) {
    super(c);
  }

  public PriorityList(Comparator comparator) {
    super();
    this.comparator = comparator;
  }

  @Override
  public boolean add(Object e) {
    if (null != comparator) {
      for (int i=0; i<size(); i++) {
        if (comparator.compare(e, get(i)) <= 0) {
          add(i, e);
          return true;
        }
      }
      addLast(e);
    }
    else
    {
      Comparable object = (Comparable) e;
      for (int i=0; i<size(); i++) {
        if (object.compareTo(get(i)) <= 0) {
          add(i, object);
          return true;
        }
      }
      addLast(object);
    }
    return true;
  }
}
