The ArrayList Short Lecture
The ArrayList Short Lecture
Introduction:
ArrayList is a part of the Java Collection Framework that provides us with dynamic arrays. It's a resizable
array implementation of the List interface. Unlike arrays, ArrayLists can dynamically grow and shrink in
size as elements are added or removed. It provides us with several utility methods to manipulate the
elements efficiently.
To use an ArrayList in Java, you need to import the java.util package at the beginning of your code.
Here's how you declare and initialize an ArrayList:
import java.util.ArrayList;
// Declaration
ArrayList<String> myArrayList;
// Initialization
Basic Operations:
1. Adding Elements:
myArrayList.add("Apple");
myArrayList.add("Banana");
myArrayList.add("Orange");
2. Accessing Elements:
3. Removing Elements:
.remove(index) - Removes the element at the specified index from the ArrayList.
.remove(object) - Removes the first occurrence of the specified element from the ArrayList.
Using Iterator
System.out.println(fruit);
// Using Iterator
while (iterator.hasNext())
System.out.println(iterator.next());
}
Here are some key methods along with examples:
1. Adding Elements:
add(E element)
Example:
fruits.add("Apple");
fruits.add("Banana");
Example:
2. Accessing Elements:
get(int index)
Example:
3. Removing Elements:
remove(int index)
Example:
remove(Object obj)
Removes the first occurrence of the specified element from the ArrayList.
Example:
fruits.remove("Apple"); // Removes the element "Apple" from the ArrayList
size()
Example:
isEmpty()
Example:
Example:
Using Iterator:
Example:
while (iterator.hasNext())
{ System.out.println(iterator.next()); }
6. Conversion to Array:
toArray()
Example:
Example:
These methods provide versatile functionality for handling ArrayLists in Java. Is there any specific
method or functionality you'd like to explore further?
Advantages of ArrayList:
Dynamic Size: ArrayLists can grow and shrink dynamically, unlike arrays.
Various Methods: It offers numerous methods for manipulation like adding, removing, accessing
elements, etc.
Disadvantages of ArrayList:
Slower Performance: Compared to arrays, ArrayLists can be slower due to their dynamic resizing nature.
Memory Overhead: ArrayLists consume more memory than arrays as they store additional information
for flexibility.