ArrayLists

You cannot change the lengths of arrays, but it would commonly be useful in many real-life scenarios to be able to insert or delete certain elements of an array. This cannot be done with arrays without creating a new longer or shorter array and copying elements to the new array. However, it can be done with ArrayLists.

ArrayLists store data just like an array using indices, but their lengths can be changed by deleting or inserting any element.

//Just Declare Variable
ArrayList<String> aList;

//Just Assign Variable
aList = newArrayList<String>();

//Declare and Assign
ArrayList<String> aList = new ArrayList<String>();

ArrayList objects have instance methods

Note that type in this case means that you specify the data type

  • Find current length

    • int size()

  • Obtain certain element

    • type get( int index )

  • Replace certain element

    • type set( int index, type x )

  • Add new element

    • type add( type x )

    • type add( int index, type x )

  • Remove certain element

    • type remove( int index )

      • The remove method removes the item at the specified index

      • It also “slides down” / reduces all higher indices by one, reducing the size of ArrayList by 1.

  • Remove all elements

    • void clear()