Java ArrayList
ArrayList
is a resizable array implementation of the List
interface in Java. It is part of the java.util
package and provides dynamic arrays that can grow as needed.
1. Creating an ArrayList
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
}
}
2. Adding Elements
Use the add()
method to add elements to the ArrayList.
list.add("Apple");
list.add("Banana");
list.add("Cherry");
3. Accessing Elements
Use the get()
method to access elements by index.
String fruit = list.get(0); // Gets the first element
System.out.println(fruit); // Outputs: Apple
4. Iterating Over an ArrayList
for (String item : list) {
System.out.println(item);
}
5. Common Methods
size()
- Returns the number of elements.remove(int index)
- Removes the element at the specified index.clear()
- Removes all elements.contains(Object o)
- Checks if the list contains the specified element.
6. Key Takeaways
ArrayList
provides dynamic arrays in Java.- It's part of the
java.util
package and implements theList
interface. - Allows duplicate elements and maintains insertion order.
- Not synchronized; use
Vector
or synchronize externally if thread safety is required.