Add method: 1. Create an ArrayList object; 2. Use the add method to add elements to the ArrayList; 3. Print the contents of the ArrayList.
Operating system for this tutorial: Windows 10 system, Dell G3 computer.
In Java, the size of an array is fixed, and elements cannot be added directly once created. If you need to add elements dynamically, consider using a collection class (such as ArrayList) instead of an array. ArrayList allows dynamic resizing and provides methods for adding elements.
The following is a simple example of using ArrayList to add elements:
import java.util.ArrayList; public class Example { public static void main(String[] args) { // 创建一个ArrayList ArrayList<String> arrayList = new ArrayList<>(); // 添加元素 arrayList.add("Element 1"); arrayList.add("Element 2"); arrayList.add("Element 3"); // 打印输出 System.out.println("ArrayList after adding elements: " + arrayList); } }
In this example, we first create an ArrayList object, and then use the add method to add elements to the ArrayList. Finally, we print out the contents of the ArrayList. ArrayList automatically resizes so elements can be added dynamically as needed.
The above is the detailed content of How to add elements to java array. For more information, please follow other related articles on the PHP Chinese website!