ArrayList ND some methods
ArrayList ND some methods
Key Points
Dynamic Resizing: Automatically grows as elements are added.
Generic: Allows specifying the type of elements ( <Type> ) it stores.
Random Access: Elements can be accessed directly by their index.
Performance: Fast for random access but slower for operations like insertion/removal in the
middle.
When to Use?
Use ArrayList when the size of the array can vary during runtime.
Prefer ArrayList over arrays if frequent insertion, deletion, or retrieval operations are required.
Why Use?
Flexible size handling.
Part of the Collections Framework, providing additional utility methods.
How to Use?
1. Import java.util.ArrayList .
2. Create an instance of ArrayList specifying the data type.
3. Use its methods to manipulate the collection.
// Add elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Access elements
System.out.println("Element at index 2: " + fruits.get(2)); // Cherry
// Replace an element
fruits.set(2, "Grapes");
1. add(E e)
Adds an element to the end of the list.
3. get(int index)
Returns the element at the specified index.
5. remove(int index)
Removes the element at the specified index.
6. remove(Object o)
Removes the first occurrence of the specified element.
7. size()
Returns the number of elements in the list.
8. isEmpty()
Checks if the list is empty.
ArrayList<String> list = new ArrayList<>();
System.out.println(list.isEmpty()); // Output: true
9. clear()
Removes all elements from the list.
10. contains(Object o)
Checks if the list contains the specified element.
11. indexOf(Object o)
Returns the index of the first occurrence of the specified element.
12. lastIndexOf(Object o)
Returns the index of the last occurrence of the specified element.
15. iterator()
Returns an iterator for the list.