Home > Java > javaTutorial > How to add elements to java array

How to add elements to java array

小老鼠
Release: 2024-01-02 16:40:04
Original
1403 people have browsed it

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.

How to add elements to java array

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);
    }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template