Java ArrayList

www.igift‮aedi‬.com

In Java, the ArrayList class is an implementation of the List interface that uses a dynamic array to store elements. It is similar to an array, but it can automatically grow and shrink as elements are added or removed. The ArrayList class is part of the Java Collections Framework and provides many methods for working with lists of objects.

Here are some of the key methods defined in the ArrayList class:

  • boolean add(E element): Adds the specified element to the end of the list.

  • void add(int index, E element): Inserts the specified element at the specified position in the list.

  • boolean addAll(Collection<? extends E> collection): Adds all elements from the specified collection to the end of the list.

  • boolean addAll(int index, Collection<? extends E> collection): Inserts all elements from the specified collection into the list, starting at the specified position.

  • E get(int index): Returns the element at the specified position in the list.

  • int indexOf(Object element): Returns the index of the first occurrence of the specified element in the list, or -1 if the element is not found.

  • int lastIndexOf(Object element): Returns the index of the last occurrence of the specified element in the list, or -1 if the element is not found.

  • E remove(int index): Removes the element at the specified position in the list.

  • boolean remove(Object element): Removes the first occurrence of the specified element from the list.

  • E set(int index, E element): Replaces the element at the specified position in the list with the specified element.

  • int size(): Returns the number of elements in the list.

  • void clear(): Removes all elements from the list.

  • Object[] toArray(): Returns an array containing all elements in the list.

  • <T> T[] toArray(T[] array): Returns an array containing all elements in the list, using the specified array if it is large enough, or creating a new array of the same type if necessary.

The ArrayList class is very useful for situations where you need to store a large number of elements that can grow or shrink dynamically. Because it uses an underlying array, the ArrayList class provides efficient random access to elements based on their index. It is also a good choice for situations where you need to add or remove elements from the middle of the list.