// 循環外定義
ReportInfo temp = new ReportInfo();
while (cursor.moveToNext()) {
temp.setXxx(...);
list.add(temp); // 每次添加同一引用
}
// 結果:list 中全是最後一條數據的引用
// 循環內定義
while (cursor.moveToNext()) {
ReportInfo temp = new ReportInfo(); // 每次新對象
temp.setXxx(...);
list.add(temp);
}
// 結果:list 包含所有不同對象
ReportInfo temp = null;
while (cursor.moveToNext()) {
temp = new ReportInfo(); // 關鍵:每次重新 new
temp.setXxx(...);
list.add(temp);
}
「引用變量放循環外,new 必須放循環內」。基本類型無此問題。