add() 方法在 ArrayList 的所有索引处都持续写入相同的对象。

huangapple go评论87阅读模式
英文:

add() method keeps writing the same object at all the indices in the ArrayList

问题

  1. 我希望每当我的程序通过for循环时都能填充我的列表然而相同的数据被写入了所有的索引
  2. Integer nunAcc = JsonPath.read(obj, "$.['Account List'].length()");
  3. JsonCharacter jChar = new JsonCharacter();
  4. List<JsonCharacter> itemList = new ArrayList<>();
  5. for(int i=0; i < nunAcc; i++) {
  6. jChar.email = JsonPath.read(obj, "$.[&#39;Account List&#39;][" + i + "].email");
  7. jChar.password = JsonPath.read(obj, "$.[&#39;Account List&#39;][" + i + "].password");
  8. jChar.characterName = JsonPath.read(obj, "$.[&#39;Account List&#39;][" + i + "].character");
  9. itemList.add(jChar);
  10. }
英文:

I want to fill my list always when my program goes through the for loop; however, the same data is written at all indices.

  1. Integer nunAcc = JsonPath.read(obj, &quot;$.[&#39;Account List&#39;].length()&quot;);
  2. JsonCharacter jChar = new JsonCharacter();
  3. List&lt;JsonCharacter&gt; itemList = new ArrayList&lt;&gt;();
  4. for(int i=0; i &lt; nunAcc; i++) {
  5. jChar.email = JsonPath.read(obj, &quot;$.[&#39;Account List&#39;][&quot; + i + &quot;].email&quot;);
  6. jChar.password = JsonPath.read(obj, &quot;$.[&#39;Account List&#39;][&quot; + i + &quot;].password&quot;);
  7. jChar.characterName = JsonPath.read(obj, &quot;$.[&#39;Account List&#39;][&quot; + i + &quot;].character&quot;);
  8. itemList.add(jChar);
  9. }

答案1

得分: 1

  1. 这样做:
  2. JsonCharacter jChar = new JsonCharacter();
  3. // ...
  4. for(int i=0; i < nunAcc; i++) {
  5. // 更新 jChar...
  6. itemList.add(jChar);
  7. }
  8. 会重复地更新然后将相同的实例添加到列表中。
  9. 在每次迭代中创建一个新的 `jChar` 实例:
  10. for(int i=0; i < nunAcc; i++) {
  11. JsonCharacter jChar = new JsonCharacter();
  12. // 更新 jChar...
  13. itemList.add(jChar);
  14. }
英文:

This:

  1. JsonCharacter jChar = new JsonCharacter();
  2. // ...
  3. for(int i=0; i &lt; nunAcc; i++) {
  4. // Update jChar...
  5. itemList.add(jChar);
  6. }

is updating then adding the same instance to the list repeatedly.

Create a new instance of jChar on each iteration:

  1. for(int i=0; i &lt; nunAcc; i++) {
  2. JsonCharacter jChar = new JsonCharacter();
  3. // Update jChar...
  4. itemList.add(jChar);
  5. }

huangapple
  • 本文由 发表于 2020年8月19日 06:30:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/63477504.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定