https://www.w3schools.com/java/java_arraylist.asp
https://www.geeksforgeeks.org/java/arraylist-in-java/
https://www.tutorialspoint.com/java/util/java_util_arraylist.htm
- An ArrayList is like a resizable array.
- It is part of the java.util package and implements the List interface.
-
The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified (if you want to add or remove elements to/from an array, you have to create a new one). While elements can be added and removed from an ArrayList whenever you want.
-Elements can be accessed using their indices, similar to arrays.
-Duplicates are allowed.
-Elements are stored in the order they are inserted.
-ArrayList is not thread-safe. To make it thread-safe, we must wrap it manually using Collections.synchronizedList().Note: ArrayList cannot hold primitive types like int, double, or char directly. we must use their wrapper classes instead:
Use Integer instead of int Use Double instead of double Use Character instead of charIt implements all optional list operations and it also permits all elements, includes null.
It provides methods to manipulate the size of the array that is used internally to store the list.
The constant factor is low compared to that for the LinkedList implementation.
The ArrayList class extends AbstractList and implements the List interface.
It implements the List interface of the collections framework .
arraylists are also known as dynamic arrays.
Hierarchy of ArrayList
It implements List Interface which is a sub-interface of Collection Interface.
ArrayList Constructors in Java
Java provides multiple constructors to create an ArrayList based on different requirements:
1. ArrayList()
Creates an empty ArrayList with default initial capacity.
ArrayList<Integer> arr = new ArrayList<>();
2. ArrayList(Collection<? extends E> c)
Creates an ArrayList initialized with elements from the specified collection.
ArrayList<String> arr = new ArrayList<>(collection);
3. ArrayList(int initialCapacity)
This constructor is used to build an array list with the initial capacity being specified.
ArrayList<Double> arr = new ArrayList<>(20);
Methods inherited
This class inherits methods from the following classes โ
java.util.AbstractList
java.lang.AbstractCollection
java.util.Object
java.util.List
Internal Implementation:
Internally an ArrayList uses a dynamically resizable array to store elements.
Dynamic Array Structure: An ArrayList is internally implemented using a dynamic array (usually an Object[] array). This array stores all the elements of the list.
Automatic Resizing: When the internal array becomes full, the ArrayList automatically increases its capacity by creating a new larger array and copying the existing elements into it.
Index-Based Access: Elements are stored in contiguous memory locations, allowing fast access using indexes (e.g., get(index)), typically in O(1) time complexity.
Element Shifting on Insert/Delete: When an element is added or removed at a specific index, the elements after that position are shifted to maintain order.
Default Capacity:When an ArrayList is created using the default constructor, its default capacity is 10.
New Capacity Calculation: The new capacity is calculated using the formula: New Capacity = Old Capacity + (Old Capacity / 2).
This increases the capacity by 50% of the old capacity.
Class declaration
Following is the declaration for java.util.ArrayList class โ
public class ArrayList<E>
extends AbstractList<E>
implements Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess
Here represents an Element. For example, if you're building an array list of Integers then you'd initialize it as
ArrayList<Integer> list = new ArrayList<Integer>();
Capacity vs Size Management
ArrayList maintains two values:
Size: number of elements currently stored
Capacity: total length of the internal array that can hold elements before resizing is required.
Need to remember
we have used Integer not int. It is because we cannot use primitive types while creating an arraylist. Instead, we have to use the corresponding wrapper classes.
Here, Integer is the corresponding wrapper class of int. To learn more, visit the Java wrapper class.
Methods of ArrayList Class
size()
Returns the length of the arraylist.
sort()
Sort the arraylist elements.
clone()
Creates a new arraylist with the same element, size, and capacity.
contains()
Searches the arraylist for the specified element and returns a boolean result.
ensureCapacity()
Specifies the total element the arraylist can contain.
isEmpty()
Checks if the arraylist is empty.
indexOf()
Searches a specified element in an arraylist and returns the index of the element.
Methods of ArrayList
add(int index, Object element)
This method inserts the specified element at the specified position index in the ArrayList. Elements from that position onwards are shifted to the right.
add(Object o)
This method appends the specified element to the end of the ArrayList.
Default behavior: always adds at the end.
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 in Java.
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 all elements from this ArrayList that are present in the specified collection.
If an element occurs multiple times in the list and is present in the collection, all its occurrences will be removed.
removeIf(Predicate 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 from Index, inclusive and to Index, 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.
Operations of ArrayList
Create an ArrayList
To use an ArrayList, you must first import it from java.util:
Example
Create an ArrayList object called cars that will store strings:
import java.util.ArrayList; // Import the ArrayList class
ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object
Now you can use methods like add(), get(), set(), and remove() to manage your list of elements.
Add Elements
To add elements to an ArrayList, use the add() method:
Example
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars);
}
}
Output
[Volvo, BMW, Ford, Mazda]
You can also add an element at a specified position by referring to the index number:
Example
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add(0, "Mazda"); // Insert element at the beginning of the list (0)
System.out.println(cars);
}
}
Output
[Mazda, Volvo, BMW, Ford]
An ArrayList keeps elements in the same order you add them, so the first item you add will be at index 0, the next at index 1, and so on.
Access an Element
To access an element in the ArrayList, use the get() method and refer to the index number:
Example
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars.get(0));
}
}
Output
Volvo
Change an Element
To modify an element, use the set() method and refer to the index number:
Example
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
cars.set(0, "Opel");
System.out.println(cars);
}
}
Output
[Opel, BMW, Ford, Mazda]
Remove an Element
To remove an element, use the remove() method and refer to the index number:
Example
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
cars.remove(0);
System.out.println(cars);
}
}
Output
[BMW, Ford, Mazda]
To remove all the elements in the ArrayList, use the clear() method:
Example
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
cars.clear();
System.out.println(cars);
}
}
Output
[]
ArrayList Size
To find out how many elements an ArrayList have, use the size method:
Example
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars.size());
}
}
Output
4
Loop Through an ArrayList
Loop through the elements of an ArrayList with a for loop, and use the size() method to specify how many times the loop should run:
Example
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
for (int i = 0; i < cars.size(); i++) {
System.out.println(cars.get(i));
}
}
}
Output
Volvo
BMW
Ford
Mazda
You can also loop through an ArrayList with the for-each loop:
Example
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
for (String i : cars) {
System.out.println(i);
}
}
}
Output
Volvo
BMW
Ford
Mazda
Other Types
Elements in an ArrayList are actually objects. In the examples above, we created elements (objects) of type "String". Remember that a String in Java is an object (not a primitive type). To use other types, such as int, you must specify an equivalent wrapper class: Integer. For other primitive types, use: Boolean for boolean, Character for char, Double for double, etc:
Example
Create an ArrayList to store numbers (add elements of type Integer):
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> myNumbers = new ArrayList<Integer>();
myNumbers.add(10);
myNumbers.add(15);
myNumbers.add(20);
myNumbers.add(25);
for (int i : myNumbers) {
System.out.println(i);
}
}
}
Output
10
15
20
25
Sort an ArrayList
class in the java.util package is the Collections class, which include the sort() method for sorting lists alphabetically or numerically:
Example
Sort an ArrayList of Strings:
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
Collections.sort(cars); // Sort cars
for (String i : cars) {
System.out.println(i);
}
}
}
Output
BMW
Ford
Mazda
Volvo
Example
Sort an ArrayList of Integers:
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class
public class Main {
public static void main(String[] args) {
ArrayList<Integer> myNumbers = new ArrayList<Integer>();
myNumbers.add(33);
myNumbers.add(15);
myNumbers.add(20);
myNumbers.add(34);
myNumbers.add(8);
myNumbers.add(12);
Collections.sort(myNumbers); // Sort myNumbers
for (int i : myNumbers) {
System.out.println(i);
}
}
}
Output
8
12
15
20
33
34
The var Keyword
use the var keyword to declare an ArrayList variable without writing the type twice. The compiler figures out the type from the value you assign.
This makes code shorter, but many developers still use the full type for clarity. Since var is valid Java, you may see it in other code, so it's good to know that it exists:
Example
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Using var instead of
// ArrayList<String> cars = new ArrayList<String>();
var cars = new ArrayList<String>(); // using var
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars);
}
}
Output
[Volvo, BMW, Ford, Mazda]
The List Interface
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
List<String> cars = new ArrayList<>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars);
}
}
Output
[Volvo, BMW, Ford, Mazda]
This means the variable (cars) is declared as a List (the interface), but it stores an ArrayList object (the actual list). Since ArrayList implements the List interface, this is possible.
It works the same way, but some developers prefer this style because it gives them more flexibility to change the type later.
Frequently asked Questions
1.How to convert an ArrayList to Array?
using the toArray() method.
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> languages = new ArrayList<>();
// add elements in the array list
languages.add("Java");
languages.add("Python");
languages.add("C++");
System.out.println("ArrayList: " + languages);
// create a new array of String type
String[] arr = new String[languages.size()];
// convert ArrayList into an array
languages.toArray(arr);
System.out.print("Array: ");
// access elements of the array
for (String item : arr) {
System.out.print(item + ", ");
}
}
}
Output
ArrayList: [Java, Python, C++]
Array: Java, Python, C++,
the toArray() method converts the languages arraylist to an array and stores it in arr. To learn more, visit Java ArrayList toArray().
2.How to convert an array to ArrayList?
use the asList() method of the Arrays class. To use asList(), we must import the java.util.Arrays package first.
import java.util.ArrayList;
import java.util.Arrays;
class Main {
public static void main(String[] args) {
// create an array of String type
String[] arr = { "Java", "Python", "C++" };
System.out.print("Array: ");
// print array
for (String str : arr) {
System.out.print(str);
System.out.print(" ");
}
// create an ArrayList from an array
ArrayList<String> languages = new ArrayList<>(Arrays.asList(arr));
System.out.println("\nArrayList: " + languages);
}
}
Output
Array: Java Python C++
ArrayList: [Java, Python, C++]
we first created an array arr of the String type. Notice the expression,
Arrays.asList(arr)
Here, the asList() method converts the array into an arraylist.
3.How to create and initialize an ArrayList in a single line?
use the Arrays.asList() method to create and initialize an arraylist in a single line.
import java.util.ArrayList;
import java.util.Arrays;
class Main {
public static void main(String[] args) {
// create and initialize ArrayList
ArrayList<String> languages = new ArrayList<>(Arrays.asList("Java", "Python", "C"));
System.out.println("ArrayList: " + languages);
}
}
// Output: ArrayList: [Java, Python, C]
4.How to convert an ArrayList to String?
use the toString() method of the ArrayList class to convert an arraylist into a string.
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> languages = new ArrayList<>();
// add elements in the ArrayList
languages.add("Java");
languages.add("Python");
languages.add("Kotlin");
System.out.println("ArrayList: " + languages);
// convert ArrayList into a String
String str = languages.toString();
System.out.println("String: " + str);
}
}
Output
ArrayList: [Java, Python, Kotlin]
String: [Java, Python, Kotlin]
5.How to create an arraylist using the List interface?
It's because the ArrayList class implements the List interface.
import java.util.ArrayList;
import java.util.List;
class Main {
public static void main(String[] args) {
// create arraylist using List
List<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Python");
languages.add("C");
System.out.println("ArrayList: " + languages);
}
}
// Output: ArrayList: [Java, Python, C]
6.What is the difference between Java ArrayList and LinkedList?
ArrayList: Implements List interface
LinkedList: Implements List, Queue, and Deque interfaces.
ArrayList:Stores a single value.
LinkedList:Stores 3 values: data, previous and next address
ArrayList:Provides the functionality of a resizable array.
LinkedList:Provides the functionality of doubly-linked list
Top comments (0)