public class StaticTest {
private static List listA;
private static List listB;
static {
listA = new ArrayList<>();
listA.add("aaa");
setB(listB); // 傳入 null
}
private static void setB(List listB) { // 參數名同欄位名
if (listB == null) {
listB = new ArrayList<>(); // 僅修改區域參數
listB.add("bbb");
}
}
public static void main(String[] args) {
System.out.println(listB == null); // true
}
}
方法參數 listB **遮蔽** 了靜態欄位 listB。方法內 listB = new ArrayList...() 僅改變**區域參數引用**,靜態欄位仍為 null。
private static void setB(List target) {
if (target == null) {
target = new ArrayList<>();
target.add("bbb");
}
listB = target; // 明確賦值給靜態欄位
}
private static void setB(List listB) {
if (listB == null) {
StaticTest.listB = new ArrayList<>(); // 類名.欄位
StaticTest.listB.add("bbb");
}
}
private static List initB() {
List b = new ArrayList<>();
b.add("bbb");
return b;
}
static {
listA = new ArrayList<>();
listA.add("aaa");
listB = initB();
}
null。