📅  最后修改于: 2023-12-03 15:01:28.483000             🧑  作者: Mango
Java ArrayList is a resizable array implementation of the List interface in Java Collections framework. It allows us to store elements in the list and provides dynamic resizing, which makes it very useful for handling large sets of data.
To declare an ArrayList in Java, you first need to import the java.util
package. After that, you can create an ArrayList object using the ArrayList
class as shown below:
import java.util.ArrayList;
ArrayList<String> list = new ArrayList<String>();
Here, String
represents the type of elements that the list can hold. You can replace it with any other data type or class name based on your requirements.
You can add elements to the list using the add()
method. It appends the specified element to the end of the list.
list.add("Element 1");
list.add("Element 2");
list.add("Element 3");
You can also insert elements at a specific position using the add(index, element)
method.
list.add(1, "Inserted Element");
You can remove elements from the list using the remove()
method. It removes the first occurrence of the specified element from the list.
list.remove("Element 1");
You can also remove elements at a specific position using the remove(index)
method.
list.remove(0);
You can access elements in the list using the get(index)
method. It returns the element at the specified index.
String element = list.get(0);
You can iterate over all the elements in the list using a for-each loop or an iterator.
for (String element : list) {
System.out.println(element);
}
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
ArrayList is a powerful data structure that provides dynamic resizing and various methods to add, remove, and access elements from the list. It is widely used in Java programming for handling collections of objects.