在 Java 中,数组的大小是固定的,无法在循环中添加元素。如果需要在循环中添加元素,可以使用 ArrayList 代替数组。ArrayList 是一个动态数组,可以根据需要动态添加或删除元素。

示例代码:

import java.util.ArrayList;

public class Example {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < 10; i++) {
            list.add(i);
        }
        System.out.println(list);
    }
}

上述代码创建了一个 ArrayList 对象,循环添加了 10 个整数元素,并打印输出了 ArrayList 的内容。输出结果为:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]。


原文地址: https://www.cveoy.top/t/topic/m9eu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录