Overview of ArrayList
Overview of ArrayList
- Declare an ArrayList
Declare an
ArrayList
with a specified type.ArrayList<String> list; // Declaration only
- Initialize an ArrayList
Use
new ArrayList<String>()
to create an instance.list = new ArrayList<String>(); // Now list is an empty ArrayList
- Add Elements to an ArrayList
Use
add()
to insert elements.list.add("A"); // Adds "A" to the list
- Remove Elements from an ArrayList
Use
remove()
by index or by value.list.remove(0); // Removes element at index 0 list.remove("A"); // Removes the first occurrence of "A"
- Clear All Elements from an ArrayList
Use
clear()
to remove all elements.list.clear(); // Empties the list
- Copy an ArrayList
Use
List.copyOf()
to make an immutable copy.List<String> immutableList = List.copyOf(list);
- Get the Size of an ArrayList
Use
size()
to get the number of elements.int size = list.size(); // Returns the size of the list
- Check for Element Containment
Use
contains()
to check if an element is in the list.boolean hasA = list.contains("A"); // Returns true if "A" is in the list
- Access an Element by Index
Use
get()
to access elements.String first = list.get(0); // Accesses the first element
- Convert an ArrayList to an Array
Use
toArray()
to convert the list to an array.String[] array = list.toArray(new String[0]); // Converts list to array
- Sort an ArrayList
Use
Collections.sort()
to sort elements in ascending order.Collections.sort(list); // Sorts list in ascending order
- Iterate Over an ArrayList
Use a for-each loop to iterate over elements.
for (String item : list) { System.out.println(item); // Prints each item in the list }