📜  一行填充arraylist java - Java (1)

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

Introduction to ArrayList in Java

ArrayList in Java is a resizable, dynamic array that provides an implementation of the List interface. It is part of the java.util package and is widely used by programmers to store and manipulate collections of objects.

Creating an ArrayList in Java

To create an ArrayList in Java, you can use the following one-liner:

ArrayList<Type> list = new ArrayList<>();

Here, Type represents the type of objects that will be stored in the ArrayList. For example, if you want to create an ArrayList to store strings, you can use:

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

Adding elements to an ArrayList

You can add elements to an ArrayList using the add() method. Here's an example:

list.add(element);

You can add elements of any type to the ArrayList.

Accessing elements in an ArrayList

You can access elements in an ArrayList using the get() method by specifying the index of the element. The index starts from 0. Here's an example:

Type element = list.get(index);

Modifying elements in an ArrayList

To modify an element in an ArrayList, you can use the set() method. Provide the index of the element you want to modify along with the updated element. Here's an example:

list.set(index, element);

Removing elements from an ArrayList

To remove an element from an ArrayList, you can use the remove() method. Provide the index of the element you want to remove. Here's an example:

list.remove(index);

You can also remove elements based on the object itself rather than the index by using the remove() method with the object as an argument.

ArrayList size

To get the size of an ArrayList (i.e., the number of elements it contains), you can use the size() method. Here's an example:

int size = list.size();

ArrayList iteration

You can iterate over the elements in an ArrayList using various methods such as a traditional for loop or an enhanced for-each loop. Here's an example of using a for-each loop:

for (Type element : list) {
    // Perform operations on each element
}

Conclusion

ArrayList in Java is a powerful collection class that provides dynamic storage for objects. Its flexibility, combined with its extensive methods, makes it a popular choice among Java programmers for handling collections.