我能做到:
import java.util.ArrayList;
public class Array {
public static void main(String args[]){
ArrayList<String> myList = new ArrayList<String>();
myList.add("S");
}
}
但是我不能这样做:
import java.util.ArrayList;
public class Array {
ArrayList<String> myList = new ArrayList<String>();
myList.add("S");
}
为什么我必须包含 main 方法?
最佳答案
因为 Java 类由方法和 block 组成。你不能有像
这样的原始语句myList.add("S");
最后,您的应用程序需要一个 Entry point并且 Java 虚拟机通过调用 main()
开始,如 JLS-12.1.4. Invoke Test.main
所述
Finally, after completion of the initialization for class
Test
(during which other consequential loading, linking, and initializing may have occurred), the methodmain
ofTest
is invoked.The method main must be declared
public
,static
, andvoid
. It must specify a formal parameter (§8.4.1) whose declared type is array ofString
.
关于java - 为什么需要 main 方法才能在类中使用 arraylist 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27553538/