gpt4 book ai didi

java - 为什么我们不能在 main() 方法之外向 ArrayList 添加元素?

转载 作者:行者123 更新时间:2023-11-29 10:10:40 25 4
gpt4 key购买 nike

public class first {

ArrayList<String> al= new ArrayList<String>();
al.add("Batman"); //it doesn't work
public static void main(String[] args) {

}
}

为什么不允许在 main 之外使用 add 方法?

最佳答案

你缺少括号。

试试这段代码:

public class first {

ArrayList<String> al= new ArrayList<String>();
{
al.add("Batman");
}

public static void main(String[] args) {

}
}

关于java - 为什么我们不能在 main() 方法之外向 ArrayList 添加元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36759173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com