There are actually two different add
methods in the ArrayList
class. The add(obj)
method adds the passed object to the end of the list. The add(index,obj)
method adds the passed object at the passed index, but first moves over any existing values to higher indices to make room for the new object.
You can also remove values from an ArrayList by using remove(index) to remove the item at the given index from the list. This will move all the other items over and decrease the size of the ArrayList by 1.
This can’t be used inside of a loop.
You can get the object at an index using someVarName = listName.get(index)
and set the object at an index using listName.set(index,obj)
. Set/Get are used after you add and remove elements to an ArrayList to change or retrieve them.
You can use this method to figure out if a value exists within an ArrayList.
You can find an object’s index inside a list. Only the first occurrence’s index will be returned. If the object doesn’t exist inside a list, -1 is returned.