ArrayList - Notes By ShariqSP
ArrayList in Java
ArrayList
is a resizable array implementation of the List
interface in Java. It provides dynamic resizing, allowing elements to be added and removed from the list, and supports random access to elements based on their index.
Definition:
An ArrayList
is a collection that maintains an underlying array to store elements. It dynamically grows and shrinks as elements are added or removed, providing flexible storage for a variable number of elements.
Methods:
- add(E element): Adds the specified element to the end of the list.
- add(int index, E element): Inserts the specified element at the specified position in the list.
- remove(int index): Removes the element at the specified position in the list.
- get(int index): Returns the element at the specified position in the list.
- size(): Returns the number of elements in the list.
- isEmpty(): Returns true if the list contains no elements.
- contains(Object obj): Returns true if the list contains the specified element.
- clear(): Removes all elements from the list.
add(E element)
Adds the specified element to the end of the list.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Create an ArrayList of integers
ArrayList list = new ArrayList<>();
// Add elements to the list
list.add(10);
list.add(20);
list.add(30);
// Display the elements
System.out.println("Elements in the list:");
System.out.println(list);
}
}
add(int index, E element)
Inserts the specified element at the specified position in the list.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Create an ArrayList of strings
ArrayList list = new ArrayList<>();
// Add elements to the list
list.add("Java");
list.add("Python");
list.add("C++");
// Insert an element at index 1
list.add(1, "JavaScript");
// Display the modified list
System.out.println("Elements after insertion:");
System.out.println(list);
}
}
remove(int index)
Removes the element at the specified position in the list.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Create an ArrayList of integers
ArrayList list = new ArrayList<>();
// Add elements to the list
list.add(10);
list.add(20);
list.add(30);
// Remove element at index 1
list.remove(1);
// Display the modified list
System.out.println("Elements after removal:");
System.out.println(list);
}
}
get(int index)
Returns the element at the specified position in the list.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Create an ArrayList of strings
ArrayList list = new ArrayList<>();
// Add elements to the list
list.add("Java");
list.add("Python");
list.add("C++");
// Get element at index 1
String element = list.get(1);
// Display the element
System.out.println("Element at index 1: " + element);
}
}
size()
Returns the number of elements in the list.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Create an ArrayList of strings
ArrayList list = new ArrayList<>();
// Add elements to the list
list.add("Java");
list.add("Python");
list.add("C++");
// Get the size of the list
int size = list.size();
// Display the size
System.out.println("Size of the list: " + size);
}
}
- An ArrayList in Java is a dynamic array implementation of the List interface that allows for the storage of elements in a resizable array-like structure.
- An ArrayList differs from an array in that it can dynamically resize itself, allowing for the addition and removal of elements without having to manually manage the size of the underlying array.
- The main features of ArrayList include dynamic resizing, fast random access to elements, efficient insertion and deletion operations (when adding/removing from the end), and the ability to store elements of any data type (via generics).
- The advantages of using ArrayList over arrays include dynamic resizing, ease of use (no need to manually manage array size), support for generics, and built-in methods for common operations such as adding, removing, and searching for elements.
- In an ArrayList, memory is managed internally by resizing the underlying array when needed. When elements are added beyond the current capacity of the ArrayList, it automatically increases its capacity by creating a new array and copying elements from the old array to the new one.
- The initial capacity of an ArrayList is 10 by default. However, it can be specified explicitly using the ArrayList constructor that takes an initial capacity parameter.
- ArrayList handles dynamic resizing by automatically increasing its capacity when needed. This is done by creating a new array with a larger capacity, copying elements from the old array to the new one, and updating the reference to the new array.
- The ensureCapacity() method in ArrayList is used to ensure that the ArrayList has enough capacity to accommodate a specified number of elements without having to resize its internal array multiple times during insertion.
- Elements can be added to an ArrayList using the add() method, which appends the element to the end of the list.
- If elements are added beyond the initial capacity of an ArrayList, it automatically increases its capacity by resizing its internal array, as described earlier.
- The main difference between ArrayList and LinkedList is in their underlying data structures. ArrayList uses a dynamic array, providing fast random access to elements but slower insertion and deletion operations at the middle or beginning of the list. LinkedList, on the other hand, uses a doubly linked list, providing fast insertion and deletion operations but slower random access to elements.
- To iterate over elements in an ArrayList, you can use a traditional for loop, an enhanced for loop (for-each loop), or the Iterator interface.
- The remove() method in ArrayList is used to remove the first occurrence of a specified element from the list. It returns true if the element was found and removed, and false otherwise.
- To search for an element in an ArrayList, you can use the indexOf() method to find the index of the first occurrence of the element, or contains() method to check if the element exists in the list.
- The performance characteristics of ArrayList operations like add(), remove(), and get() are generally O(1) for adding/removing from the end of the list, O(n) for adding/removing from the middle, and O(1) for random access (get() method) due to its dynamic array implementation.
Advantages:
- Dynamic Size: ArrayList provides dynamic sizing, allowing for the addition and removal of elements at runtime without needing to specify the size beforehand. This flexibility makes ArrayList suitable for scenarios where the size of the collection may vary.
- Random Access: ArrayList allows for fast random access to elements using an index. This means that elements can be quickly retrieved or modified by their position in the list, making ArrayList efficient for operations that require frequent access to elements at specific positions.
- Standardized API: ArrayList implements the List interface, providing a standardized set of methods for adding, removing, and accessing elements. This makes ArrayList easy to use and interoperable with other List implementations, simplifying code maintenance and improving code readability.
- Automatic Resizing: ArrayList automatically resizes itself when the number of elements exceeds its capacity. This resizing is done efficiently to minimize performance overhead, ensuring that ArrayList remains efficient even for large datasets.
Disadvantages:
- Memory Overhead: ArrayList requires additional memory to maintain its internal array structure. This overhead can become significant, especially when dealing with large datasets or when the initial capacity is set too high.
- Insertion and Deletion: While ArrayList provides fast random access, insertion and deletion operations at arbitrary positions can be slower, especially when elements need to be shifted to accommodate the change in size. LinkedList may be more efficient for frequent insertion and deletion in the middle of the list.
- Not Thread-safe: ArrayList is not thread-safe by default. If multiple threads access an ArrayList concurrently, it can lead to data corruption or undefined behavior. Synchronization mechanisms need to be applied externally to ensure thread safety if needed, increasing complexity and potentially impacting performance.
- Primitive Type Limitation: ArrayList can only store objects and cannot directly store primitive data types. Primitive data types need to be wrapped in their respective wrapper classes (e.g., Integer for int) to be stored in an ArrayList, which can lead to boxing and unboxing overhead.
Interview Questions and MCQs on ArrayList in Java
Interview Questions:
- What is an ArrayList in Java?
- How is an ArrayList different from an array?
- Explain the main features of ArrayList.
- What are the advantages of using ArrayList over arrays?
- How is memory managed in an ArrayList?
- What is the initial capacity of an ArrayList?
- How does ArrayList handle dynamic resizing?
- What is the role of the ensureCapacity() method in ArrayList?
- How do you add elements to an ArrayList?
- What happens if you add elements beyond the initial capacity of an ArrayList?
- Explain the difference between ArrayList and LinkedList.
- How do you iterate over elements in an ArrayList?
- What is the purpose of the remove() method in ArrayList?
- How do you search for an element in an ArrayList?
- What are the performance characteristics of ArrayList operations like add(), remove(), and get()?
Multiple Choice Questions (MCQs):
- Which of the following statements is true about ArrayList?
a) ArrayList is a resizable array
b) ArrayList is a fixed-size array
c) ArrayList can only store primitive data types
d) ArrayList is a synchronized collection
Answer: a) ArrayList is a resizable array - Which method is used to add an element to the end of an ArrayList?
a) addLast()
b) insert()
c) add()
d) append()
Answer: c) add() - What is the default initial capacity of an ArrayList?
a) 5
b) 10
c) 15
d) 20
Answer: b) 10 - Which method is used to remove an element from an ArrayList?
a) removeFirst()
b) delete()
c) remove()
d) erase()
Answer: c) remove() - How do you access an element at a specific index in an ArrayList?
a) get(index)
b) getElement(index)
c) access(index)
d) retrieve(index)
Answer: a) get(index)