ArrayList Methods in java:
In Java, ArrayList is a part of the Java Collections Framework and provides many useful methods to store, manipulate, and retrieve data dynamically.
Commonly used ArrayList Methods:
1. Adding Elements:
- add(E e)-> Adds the elements at the end
Example:
List.add("Apple");
- add(int index, E e) → Adds an element at the specified index.
Example:
list.add(1, "Banana");
- addAll(Collection c) → Adds all elements from another collection.
Example:
list.addAll(otherList);
2.Accessing Elements:
- get(int index) → Returns the element at the given index.
Examples:
String fruit = list.get(0);
3. Changing Elements:
- set(int index, E e) → Updates the element at the specified index.
Example:
list.set(1, "Mango");
4. Removing Elements:
- remove(int index) → Removes the element at the given index.
Example:
list.remove(2);
- remove(Object o) → Removes the first occurrence of the given element.
Example:
list.remove("Apple");
- clear() → Removes all elements from the list.
Example:
list.clear();
- Searching Elements:
- contains(Object o) → Returns true if the list contains the element.
Example:
list.contains("Mango");
- indexOf(Object o) → Returns the first index of the element, or -1 if not found.
Example:
int index = list.indexOf("Banana");
- lastIndexOf(Object o) → Returns the last index of the element.
Example:
int index = list.lastIndexOf("Apple");
- Size and Empty Check:
- size() → Returns the number of elements in the list.
EXample:
int count = list.size();
- isEmpty() → Returns true if the list is empty.
Example:
isEmpty() → Returns true if the list is empty.
7. Converting to Array:
- toArray() → Converts the list to an array.
Example:
Object[] arr = list.toArray();
8. Iteration:
iterator() → Returns an iterator to traverse the list.
listIterator() → Returns a list iterator for forward and backward traversal.
Example:
Iterator<String> it = list.iterator();
9. Sorting (Using Collections):
Example:
Collections.sort(list);
Top comments (0)