If you have any query feel free to chat us!
Happy Coding! Happy Learning!
ArrayList
in Java provides a wide range of methods to manipulate the list of elements it holds. Here are some of the commonly used methods of the ArrayList
class:
add(E element)
: Appends the specified element to the end of the list.add(int index, E element)
: Inserts the specified element at the specified position in the list.get(int index)
: Returns the element at the specified index.set(int index, E element)
: Replaces the element at the specified index with the specified element.remove(int index)
: Removes the element at the specified index from the list.remove(Object o)
: Removes the first occurrence of the specified element from the list.clear()
: Removes all elements from the list.size()
: Returns the number of elements in the list.isEmpty()
: Returns true if the list is empty, otherwise false.contains(Object o)
: Returns true if the list contains the specified element, otherwise false.indexOf(Object o)
: Returns the index of the first occurrence of the specified element, or -1 if not found.lastIndexOf(Object o)
: Returns the index of the last occurrence of the specified element, or -1 if not found.subList(int fromIndex, int toIndex)
: Returns a new ArrayList
containing elements from fromIndex
(inclusive) to toIndex
(exclusive).toArray()
: Converts the ArrayList
to a regular array of objects.toArray(T[] a)
: Converts the ArrayList
to an array of the specified type T
.ArrayList
.javaCopy code
import java.util.ArrayList;
public class ArrayListMethodsExample {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
// Adding elements
numbers.add(10);
numbers.add(20);
numbers.add(30);
// Accessing elements
int secondNumber = numbers.get(1); // 20
// Removing elements
numbers.remove(0); // Remove 10
// Size and checking empty
int size = numbers.size(); // 2
boolean isEmpty = numbers.isEmpty(); // false
// Searching elements
boolean contains30 = numbers.contains(30); // true
int index = numbers.indexOf(30); // 1
// Sublist operations
ArrayList<Integer> sublist = numbers.subList(0, 1); // [20]
// Converting to array
Integer[] numbersArray = numbers.toArray(new Integer[0]);
}
}
These are just some of the many methods available in the ArrayList
class. The Java ArrayList
provides a rich set of operations to manage and manipulate collections of elements efficiently. For more details and additional methods, you can refer to the official Java documentation for the ArrayList
class.
Comments: 0