In Java SE 17, an ArrayList maintains order through its underlying data structure, which is a dynamically resizing array. Here's how it keeps order:
- Insertion Order:
- Elements in an ArrayList are stored in the order they are added. When you use methods like add(E e), the element e is appended to the end of the list. If you use add(int index, E element), the element is inserted at the specified position, shifting all elements after that position one place to the right.
- Index-Based Access:
- Each element in an ArrayList has an index starting from 0. The order is preserved by maintaining the association of each element with its index. When you retrieve an element using get(int index), you get the element at that exact position.
- Dynamic Resizing:
- When the number of elements exceeds the capacity of the internal array, ArrayList automatically increases its size. This resizing operation copies all elements to a new, larger array, preserving their order.
- Modification:
- Methods like set(int index, E element) replace the element at the given index without changing the order of other elements. Similarly, remove(int index) removes the element at the specified index, shifting all subsequent elements one position to the left to maintain order.
Here's a simple example to illustrate:
import java.util.ArrayList;
public class ArrayListOrderExample {
public static void main(String[] args) {
ArrayList list = new ArrayList<>();
// Adding elements in order
list.add("First");
list.add("Second");
list.add("Third");
// Inserting an element at a specific index
list.add(1, "Inserted");
// Printing the list to show order
System.out.println(list);
// Modifying an element
list.set(2, "Modified");
// Removing an element
list.remove(0);
System.out.println(list);
}
}
This code would output:
[First, Inserted, Second, Third]
[Inserted, Modified, Third]
In summary, ArrayList in Java SE 17 uses an array internally to keep elements in the exact order they were inserted or modified, providing methods to maintain this order through insertion, removal, and modification operations.