import java.util.ArrayList;
import java.util.List;
public class Test {
List<First> first ;
public List<First> getFirst() {
return first;
}
public void setFirst(List<First> first) {
this.first = first;
}
public static void main(String[] args) {
Test test = new Test();
int i = 10 , j = 8 ;
First f ;
List<First> list ;
while (i>0){
list = new ArrayList<First>() ;
f = new First();
f.setK(j++);
f.setI("==");
list.add(f);
i--;
}
test.setFirst(list);
for(First first : list){
System.out.println(first.getK());
}
}
}
class First {
private String i ;
private int k ;
public String getI() {
return i;
}
public void setI(String i) {
this.i = i;
}
public int getK() {
return k;
}
public void setK(int k) {
this.k = k;
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The local variable list may not have been initialized
The local variable list may not have been initialized
at Test.main(Test.java:26)
while里面不是初始化了么,而list是公共变量, test.setFirst(list);应该能得到list把?
编辑器怎么知道程序一定能进while循环呢? 你的while循环是i>0 编译怎么知道i是多少呢?它说的是可能会还没被初始化
因为如果i<=0,就会跳过循环,直接到test.setFirst(list);但是这时候list并没有初始化。