java ArrayList
时间: 2024-05-15 20:19:20 浏览: 5
In Java, an ArrayList is a resizable array implementation of the List interface. It allows dynamic resizing of the array as elements are added or removed. The ArrayList class provides various methods to add, remove, and modify elements in the list.
Some of the commonly used methods of ArrayList class are:
1. add(E element): Adds an element at the end of the list.
2. add(int index, E element): Inserts an element at the specified index.
3. remove(int index): Removes the element at the specified index.
4. clear(): Removes all the elements from the list.
5. size(): Returns the number of elements in the list.
6. get(int index): Returns the element at the specified index.
7. set(int index, E element): Replaces the element at the specified index with the specified element.
Here's an example of how to use an ArrayList in Java:
```
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<String>();
// adding elements to the list
names.add("John");
names.add("Jane");
names.add("Mike");
// iterating over the list and printing the elements
for (String name : names) {
System.out.println(name);
}
// removing an element from the list
names.remove(1);
// getting the size of the list
System.out.println("Size of the list: " + names.size());
}
}
```