Search code examples
javaarraylistabstract-data-type

ADT comprehension in Java - Adding an element to a tail of an Arraylist


Im only starting to learn about abstract data structure. Previously im able to add elements to list with a specified types. Now im learning about an abstract type, in this case <T>

In this case, how do i add an element?

I want to add an element in the tail of the arraylist. this is what I have done.

public class Q3ArrayList<T> {


    private static final int INITIAL_SIZE = 2;
    private static final double GROWTH_FACTOR = 1.5;

    T[] values = (T[]) new Object[INITIAL_SIZE];
    int elements = 0; //NUMBER OF ELEMENTS IN THE LIST

    /**
     * Add a value to the tail of the list.
     *
     * @param value The value to be added.
     */
    public void add(T value) {

    }

   public void remove(int index) {
    values[elements--] = remove(index);

}

Solution

  • void add(T element){
    values[elements++] = element;
    }
    

    This will add element at the end of your array, and increase the value of elements by one, so you can track number of elements in array.