ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package.
Example: The following implementation demonstrates how to create and use an ArrayList.
[1, 2, 3, 4, 5] [1, 2, 3, 5] 1 2 3 5
Performing Various Operations on ArrayList
Let’s see how to perform some basics operations on the ArrayList.
1. Adding Elements: In order to add an element to an ArrayList, we can use the add() method. This method is overloaded to perform multiple operations based on different parameters. They are:
- add(Object): This method is used to add an element at the end of the ArrayList.
- add(int index, Object): This method is used to add an element at a specific index in the ArrayList.
[Geeks, For, Geeks]
2. Changing Elements: After adding the elements, if we wish to change the element, it can be done using the set() method. Since an ArrayList is indexed, the element which we wish to change is referenced by the index of the element. Therefore, this method takes an index and the updated element which needs to be inserted at that index.
Initial ArrayList [Geeks, Geeks, Geeks] Updated ArrayList [Geeks, For, Geeks]
3. Removing Elements: In order to remove an element from an ArrayList, we can use the remove() method. This method is overloaded to perform multiple operations based on different parameters. They are:
- remove(Object): This method is used to simply remove an object from the ArrayList. If there are multiple such objects, then the first occurrence of the object is removed.
- remove(int index): Since an ArrayList is indexed, this method takes an integer value which simply removes the element present at that specific index in the ArrayList. After removing the element, all the elements are moved to the left to fill the space and the indices of the objects are updated.
Initial ArrayList [Geeks, For, Geeks] After the Index Removal [Geeks, Geeks] After the Object Removal [Geeks]
4. Iterating the ArrayList: There are multiple ways to iterate through the ArrayList. The most famous ways are by using the basic for loop in combination with a get() method to get the element at a specific index and the advanced for loop.
Geeks For Geeks Geeks For Geeks
- ArrayList inherits AbstractList class and implements List interface.
- ArrayList is initialized by the size. However, the size is increased automatically if the collection grows or shrinks if the objects are removed from the collection.
- Java ArrayList allows us to randomly access the list.
- ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper class for such cases.
- ArrayList in Java can be seen as a vector in C++.
- ArrayList is not Synchronized. Its equivalent synchronized class in Java is Vector.
Let’s understand the Java ArrayList in depth. Look at the below image:
In the above illustration, AbstractList, CopyOnWriteArrayList and the AbstractSequentialList are the classes which implement the list interface. A separate functionality is implemented in each of the mentioned classes. They are:
- AbstractList: This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.
- CopyOnWriteArrayList: This class implements the list interface. It is an enhanced version of ArrayList in which all the modifications(add, set, remove, etc.) are implemented by making a fresh copy of the list.
- AbstractSequentialList: This class implements the Collection interface and the AbstractCollection class. This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.
How ArrayList work internally?
Since ArrayList is a dynamic array and we do not have to specify the size while creating it, the size of the array automatically increases when we dynamically add and remove items. Though the actual library implementation may be more complex, the following is a very basic idea explaining the working of the array when the array becomes full and if we try to add an item:
- Creates a bigger sized memory on heap memory (for example memory of double size).
- Copies the current memory elements to the new memory.
- New item is added now as there is bigger memory available now.
- Delete the old memory.
Constructors in the ArrayList
In order to create an ArrayList, we need to create an object of the ArrayList class. The ArrayList class consists various constructors which allows the possible creation of the array list. The following are the constructors available in this class:
- ArrayList(): This constructor is used to build an empty array list. If we wish to create an empty ArrayList with the name arr, then, it can be created as:
ArrayList arr = new ArrayList();
- ArrayList(Collection c): This constructor is used to build an array list initialized with the elements from the collection c. Suppose, we wish to create an arraylist arr which contains the elements present in the collection c, then, it can be created as:
ArrayList arr = new ArrayList(c);
- ArrayList(int capacity): This constructor is used to build an array list with initial capacity being specified. Suppose we wish to create an ArrayList with the initial size being N, then, it can be created as:
ArrayList arr = new ArrayList(N);
Note: You can also create a generic ArrayList:
// Creating generic integer ArrayList ArrayList<Integer> arrli = new ArrayList<Integer>();
Methods in Java ArrayList
Here, ?(Question Mark) means that method can accept any type of objects even custom objects.
|add(int index, Object element)||This method is used to insert a specific element at a specific position index in a list.|
|add(Object o)||This method is used to append a specific element to the end of a list.|
|addAll(Collection C)||This method is used to append all the elements from a specific collection to the end of the mentioned list, in such an order that the values are returned by the specified collection’s iterator.|
|addAll(int index, Collection C)||Used to insert all of the elements starting at the specified position from a specific collection into the mentioned list.|
|clear()||This method is used to remove all the elements from any list.|
|clone()||This method is used to return a shallow copy of an ArrayList.|
|contains?(Object o)||Returns true if this list contains the specified element.|
|ensureCapacity?(int minCapacity)||Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.|
|forEach?(Consumer<? super E> action)||Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.|
|get?(int index)||Returns the element at the specified position in this list.|
|indexOf(Object O)||The index the first occurrence of a specific element is either returned, or -1 in case the element is not in the list.|
|isEmpty?()||Returns true if this list contains no elements.|
|lastIndexOf(Object O)||The index of the last occurrence of a specific element is either returned or -1 in case the element is not in the list.|
|listIterator?()||Returns a list iterator over the elements in this list (in proper sequence).|
|listIterator?(int index)||Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.|
|remove?(int index)||Removes the element at the specified position in this list.|
|remove?(Object o)||Removes the first occurrence of the specified element from this list, if it is present.|
|removeAll?(Collection> c)||Removes from this list all of its elements that are contained in the specified collection.|
|removeIf?(Predicate super E> filter)||Removes all of the elements of this collection that satisfy the given predicate.|
|removeRange?(int fromIndex, int toIndex)||Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.|
|retainAll?(Collection<?> c)||Retains only the elements in this list that are contained in the specified collection.|
|set?(int index, E element)||Replaces the element at the specified position in this list with the specified element.|
|size?()||Returns the number of elements in this list.|
|spliterator?()||Creates a late-binding and fail-fast Spliterator over the elements in this list.|
|subList?(int fromIndex, int toIndex)||Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.|
|toArray()||This method is used to return an array containing all of the elements in the list in the correct order.|
|toArray(Object O)||It is also used to return an array containing all of the elements in this list in the correct order same as the previous method.|
|trimToSize()||This method is used to trim the capacity of the instance of the ArrayList to the list’s current size.|
Also see: Array vs ArrayList in Java
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- ArrayList of ArrayList in Java
- Java.util.ArrayList.addall() method in Java
- Java.util.ArrayList.add() Method in Java
- Java.util.Arraylist.indexOf() in Java
- Arraylist.contains() in Java
- Arraylist lastIndexOf() in Java with example
- ArrayList trimToSize() in Java with example
- ArrayList isEmpty() in Java with example
- How to get ArrayList from Stream in Java 8
- ArrayList vs LinkedList in Java
- ArrayList vs. HashMap in Java
- Get first and last elements from ArrayList in Java
- Array vs ArrayList in Java
- Custom ArrayList in Java
- Initialize an ArrayList in Java
- Reverse an ArrayList in Java
- Array of ArrayList in Java
- Synchronization of ArrayList in Java
- Vector vs ArrayList in Java
- How to make an ArrayList read only in Java
Improved By : KaashyapMSK