英文:
add() method keeps writing the same object at all the indices in the ArrayList
问题
我希望每当我的程序通过for循环时,都能填充我的列表;然而,相同的数据被写入了所有的索引。
Integer nunAcc = JsonPath.read(obj, "$.['Account List'].length()");
JsonCharacter jChar = new JsonCharacter();
List<JsonCharacter> itemList = new ArrayList<>();
for(int i=0; i < nunAcc; i++) {
jChar.email = JsonPath.read(obj, "$.['Account List'][" + i + "].email");
jChar.password = JsonPath.read(obj, "$.['Account List'][" + i + "].password");
jChar.characterName = JsonPath.read(obj, "$.['Account List'][" + i + "].character");
itemList.add(jChar);
}
英文:
I want to fill my list always when my program goes through the for loop; however, the same data is written at all indices.
Integer nunAcc = JsonPath.read(obj, "$.['Account List'].length()");
JsonCharacter jChar = new JsonCharacter();
List<JsonCharacter> itemList = new ArrayList<>();
for(int i=0; i < nunAcc; i++) {
jChar.email = JsonPath.read(obj, "$.['Account List'][" + i + "].email");
jChar.password = JsonPath.read(obj, "$.['Account List'][" + i + "].password");
jChar.characterName = JsonPath.read(obj, "$.['Account List'][" + i + "].character");
itemList.add(jChar);
}
答案1
得分: 1
这样做:
JsonCharacter jChar = new JsonCharacter();
// ...
for(int i=0; i < nunAcc; i++) {
// 更新 jChar...
itemList.add(jChar);
}
会重复地更新然后将相同的实例添加到列表中。
在每次迭代中创建一个新的 `jChar` 实例:
for(int i=0; i < nunAcc; i++) {
JsonCharacter jChar = new JsonCharacter();
// 更新 jChar...
itemList.add(jChar);
}
英文:
This:
JsonCharacter jChar = new JsonCharacter();
// ...
for(int i=0; i < nunAcc; i++) {
// Update jChar...
itemList.add(jChar);
}
is updating then adding the same instance to the list repeatedly.
Create a new instance of jChar
on each iteration:
for(int i=0; i < nunAcc; i++) {
JsonCharacter jChar = new JsonCharacter();
// Update jChar...
itemList.add(jChar);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论