Class SortedVector<T extends Comparable<T>>

java.lang.Object
imagingbook.common.util.SortedVector<T>
Type Parameters:
T - the generic element type

public class SortedVector<T extends Comparable<T>> extends Object
Defines a generic container for "comparable" elements that allows sorted insertions without exceeding the predefined capacity. This implementation is based on PriorityQueue. New items are inserted using the elements natural ordering or a supplied comparator. Once the predefined capacity is exceeded, redundant items are removed from the underlying priority queue. Example (using natural ordering of Integer):
     SortedVector<Integer> sv = new SortedVector<>(new Integer[3]);
     sv.insert(5);
     sv.insert(2);
     sv.insert(9);
     sv.insert(1);
     Integer[] arr = sv.getArray();       // [9, 5, 2]
 
Version:
2022/12/14
  • Constructor Details

    • SortedVector

      public SortedVector(T[] arr, Comparator<T> comp)
      Constructor using a specific comparator. The length of the supplied array specifies the capacity of the new container.
      Parameters:
      arr - an array of the generic element type (content is ignored)
      comp - comparator
    • SortedVector

      public SortedVector(T[] arr)
      Constructor, using the natural-order comparator of the generic element type. The length of the supplied array specifies the capacity of this container.
      Parameters:
      arr - an array of the generic element type (content is ignored)
  • Method Details

    • add

      public void add(T item)
      Tries to adds a new item to this SortedVector instance. It is inserted into the vector if it is "greater" than the current "smallest" element (head) in this vector, otherwise it is discarded. The meaning of "greater" and "smallest" depend on the associated comparator (see SortedVector(Comparable[], Comparator)). Items contained in the vector are not replaced by new items with identical values.
      Parameters:
      item - to add
    • getArray

      public T[] getArray()
      Returns an array holding the elements of this SortedVector instance. The elements are sorted according to the specified comparator. The length of the array is equal to the value returned by size(); the maximum length equals the capacity of this vector. If the SortedVector was completely filled to its capacity, the returned array is identical to the one that was passed to the constructor. The array contains no null elements. The returned array is sorted in descending order, such that the "greatest" item added to the SortedVector appears at its front (i.e., in position 0).
      Returns:
      a sorted array of elements
    • size

      public int size()
      Returns the current number of non-null items in this vector.
      Returns:
      the number of contained items
    • toString

      public String toString()
      Overrides:
      toString in class Object