我試圖用數字填充ArrayList<Integer>
。當我調用主方法中的方法時,編譯器會抱怨如何從一個方法填充ArrayList <Integer>?
Exception in thread "main"`
java.lang.NullPointerException
at PrimeSum.setGeneralArray(PrimeSum.java:11)
at PrimeSum.main(PrimeSum.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Process finished with exit code 1
這是我的代碼示例。
public class PrimeSum {
private ArrayList<Integer> generalArray;
private int limit;
public void setGeneralArray() {
for(int i = 2; i < 2000001; i++) {
generalArray.add(i);
}
}
// ...
// This is how I call on the method.
public static void main(String[] args) {
PrimeSum ps = new PrimeSum();
ps.setGeneralArray();
// ...
我做錯了什麼?