Java ArrayList-interview
Q1. What is the difference between ArrayList and LinkedList?
ArrayList is backed by a dynamic array, while LinkedList uses a doubly-linked list. ArrayList gives faster access (O(1)), but slower insert/delete in the middle.
Q2. How does ArrayList handle resizing internally?
When full, it increases capacity by 1.5 times the old size and copies old elements into the new array.
Q3. What is the difference between size() and capacity() in ArrayList?
size() = number of elements currently stored.
capacity() = total allocated space in the backing array.
Q4. What happens if you try to access an element at an index greater than size()?
It throws IndexOutOfBoundsException.
Q5. How do you make an ArrayList read-only?
By using Collections.unmodifiableList(arrayList).
Q6. Can two ArrayLists be compared directly with ==?
No, == checks reference equality. Use .equals() to compare contents.
Q7. What is the difference between remove(int index) and remove(Object o) in ArrayList?
remove(int index) removes the element at a specific position.
remove(Object o) removes the first occurrence of the object.