Class SimpleArray<T>

  • Type Parameters:
    T - type of elements in the array
    All Implemented Interfaces:
    Iterable<T>

    public class SimpleArray<T>
    extends Object
    implements Iterable<T>
    An array that can be iterated over.

    This class is useful in a few cases:

    • You expect that there are a large, but unknown, number of elements that will be added. This class grows its internal storage array more aggressively to avoid multiple array copying. The back side to this is that it may waste more memory.
    • You want to reuse a preallocated array.
    If you don't have any of those needs, then you might as well use a standard ArrayList instead.

    • Constructor Detail

      • SimpleArray

        public SimpleArray​(T[] initial)
        Create an instance backed by an array. The array content will be overwritten with elements that are subsequently added.
        Parameters:
        initial - array to use for storage
      • SimpleArray

        public SimpleArray​(T[] initial,
                           int size)
        Create an instance backed by an array with a specified number of preallocated elements. The array content after the preallocated elements will be overwritten with elements that are subsequently added.
        Parameters:
        initial - array to use for storage
        size - number of preallocated elements
    • Method Detail

      • get

        public T get​(int index)
        Get the element at the specified index.
        Parameters:
        index - element index
        Returns:
        element at index
      • add

        public void add​(T element)
        Add an element to the end of the list.
        Parameters:
        element - element to add
      • addAll

        public void addAll​(T[] src)
        Add all elements from an array.
        Parameters:
        src - array containing elements to add
      • copyTo

        public void copyTo​(T[] dst,
                           int offset)
        Copy all elements from the backing array to another array. The destination array must be large enough to fit all elements.
        Parameters:
        dst - array to copy elements to
        offset - starting position in the destination array
      • calculateNewCapacity

        protected int calculateNewCapacity​(int currentCapacity)
      • size

        public int size()
        Get the number of stored elements. Note that this is not the same as the size of the backing array.
        Returns:
        the number of stored elements
      • clear

        public void clear()
        Clear all elements. Note that the backing array is not cleared.
      • elements

        public T[] elements()
        Get an array with all elements. The array length will be equal to the number of elements.
        Returns:
        an array with all elements