Java ArrayList is a class in the Java Collections Framework that provides a resizable array implementation of the List interface. It is similar to an array, but with the added benefit of being able to dynamically resize itself as elements are added or removed. This makes it a popular choice for storing and manipulating collections of data in Java programs.
The ArrayList class is part of the java.util package and can be imported into a Java program using the following statement:
import java.util.ArrayList;
Once imported, an ArrayList object can be created using the following syntax:
ArrayList<DataType> listName = new ArrayList<>();
Where DataType is the type of data that will be stored in the ArrayList and listName is the name of the ArrayList object.
For example, to create an ArrayList of integers, the following code can be used:
ArrayList<Integer> numbers = new ArrayList<>();
Once an ArrayList object has been created, elements can be added to it using the add() method:
numbers.add(10);
numbers.add(20);
numbers.add(30);
Elements can also be removed from the ArrayList using the remove() method:
numbers.remove(1); // removes the element at index 1 (20)
The size of the ArrayList can be obtained using the size() method:
int size = numbers.size(); // returns 2
Elements can be accessed using their index in the ArrayList:
int firstElement = numbers.get(0); // returns 10
The ArrayList class also provides several other useful methods for manipulating and accessing elements, such as contains(), indexOf(), and subList().
One important thing to note about ArrayLists is that they can only store objects, not primitive data types. This means that if you want to store a primitive data type in an ArrayList, you must use its corresponding wrapper class. For example, to store an int in an ArrayList, you would use the Integer wrapper class:
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(Integer.valueOf(10));
Overall, the Java ArrayList class provides a powerful and flexible way to store and manipulate collections of data in Java programs.
Here are some examples of how to use the Java ArrayList class:
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.remove(1); // removes "Bob"
String firstElement = names.get(0); // returns "Alice"
for (String name : names) {
System.out.println(name);
}
This will output:
Alice
Charlie
boolean containsBob = names.contains("Bob"); // returns false
int index = names.indexOf("Charlie"); // returns 1
List<String> subList = names.subList(0, 2); // returns ["Alice", "Charlie"]