import java.util.ArrayList;
import java.util.Collections;

/**
 * Class that extends ArrayList to keep the Comparable items sorted.
 *   @author Dave Reed
 *   @version 11/25/17
 */
public class SortedArrayList<E extends Comparable<? super E>> extends ArrayList<E> {
    /**
     * Constructs an empty SortedArrayList
     */
    public SortedArrayList() {
        super();
    }
    
    /**
     * Adds an item to the SortedArrayList, maintaining order.
     *   @param item the item to be added
     *   @return true if the add was successful, else false
     */
    public boolean add(E item) {
        int index = Collections.binarySearch(this, item);
        if (index < 0) {
            index = -index - 1;
        }

        super.add(index, item);
        return true;
    } 
    
    /**
     * Sets the item at a given index, reorderings as necessary.
     *   @param index the index of the item to be replaced
     *   @param item the new item
     *   @return the item previously stored at that index
     */
    public E set(int index, E item) {
        E oldItem = this.remove(index);
        this.add(item);
        return oldItem;
    }
    
    /**
     * Locates the index of the desired item
     *   @param the object to be searched for
     *   @return the index where that object is found, or -1 if not found
     */
    public int indexOf(Object item) {
        try {
          int index = Collections.binarySearch(this, (E)item);
          if (index >= 0) {
              return index;
          }
          return -1;
        }
        catch (ClassCastException e) {
            return -1;
        }
    }
}
