Sobes.tech
Junior — Middle

When accessing an element by index, which data structure provides a faster operation: ArrayList or LinkedList?

sobes.tech AI

Answer from AI

Accessing an element by index in Java's ArrayList provides faster operation compared to LinkedList.

The reason is that ArrayList is based on an array, and access to an element by index is an O(1) operation, as it can directly access the required cell.

In LinkedList, elements are linked through nodes, and to get an element by index, you need to traverse the list from the beginning or end to the desired position, which takes O(n) time.

Example:

ArrayList<String> arrayList = new ArrayList<>();
LinkedList<String> linkedList = new LinkedList<>();

// Adding elements
for (int i = 0; i < 1000; i++) {
    arrayList.add("Element " + i);
    linkedList.add("Element " + i);
}

// Fast access in ArrayList
String element = arrayList.get(500); // O(1)

// Slow access in LinkedList
String element2 = linkedList.get(500); // O(n)

Therefore, for frequent index access, it's better to use ArrayList.