📜  arraylist 到 java (1)

📅  最后修改于: 2023-12-03 14:59:23.288000             🧑  作者: Mango

ArrayList in Java

What is ArrayList?

ArrayList is a class in the Java programming language that provides a resizable array-like data structure. It implements the List interface and uses dynamic arrays internally to store elements. This means that unlike normal arrays, an ArrayList can grow and shrink in size as elements are added or removed.

Declaration and Initialization

To use an ArrayList, you need to import the java.util package and create an instance of the class using the new keyword. Here's an example:

import java.util.ArrayList;

ArrayList<String> names = new ArrayList<>();

In the above code snippet, we declare and initialize an ArrayList named names that can store String objects.

Adding Elements

You can add elements to an ArrayList using the add() method. Here are a few examples:

names.add("John");
names.add("Mary");
names.add("David");

The elements will be added to the end of the ArrayList.

Accessing Elements

You can access elements in an ArrayList using their index. The index starts at 0 for the first element and goes up to size() - 1.

String name = names.get(0);
System.out.println(name);  // Output: John
Updating Elements

To update an element at a specific index in the ArrayList, use the set() method.

names.set(1, "Alice");
System.out.println(names);  // Output: [John, Alice, David]

In the above example, we update the element at index 1 to "Alice".

Removing Elements

You can remove elements from an ArrayList using the remove() method. There are two versions of the method: one that takes an index and removes the element at that index, and another that takes an object and removes the first occurrence of that object.

names.remove(2);  // Removes the element at index 2
names.remove("John");  // Removes the first occurrence of "John"
ArrayList Size

To get the number of elements in an ArrayList, you can use the size() method.

int size = names.size();
System.out.println(size);  // Output: 2
Iterating over ArrayList

You can iterate over the elements of an ArrayList using a for-each loop or a traditional for loop.

for (String name : names) {
    System.out.println(name);
}
Conclusion

ArrayList in Java is a powerful data structure that provides a flexible way to store and manipulate collections of elements. It is widely used by programmers due to its simplicity and efficiency.

Note: Don't forget to import the java.util.ArrayList class to use ArrayList in your program.