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

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

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, "$.[&#39;Account List&#39;][" + i + "].email");
    jChar.password = JsonPath.read(obj, "$.[&#39;Account List&#39;][" + i + "].password");
    jChar.characterName = JsonPath.read(obj, "$.[&#39;Account List&#39;][" + 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, &quot;$.[&#39;Account List&#39;].length()&quot;);         
JsonCharacter jChar = new JsonCharacter();

List&lt;JsonCharacter&gt; itemList = new ArrayList&lt;&gt;();
                    
for(int i=0; i &lt; nunAcc; i++) {                       
    jChar.email = JsonPath.read(obj, &quot;$.[&#39;Account List&#39;][&quot; + i + &quot;].email&quot;);
    jChar.password = JsonPath.read(obj, &quot;$.[&#39;Account List&#39;][&quot; + i + &quot;].password&quot;);
    jChar.characterName = JsonPath.read(obj, &quot;$.[&#39;Account List&#39;][&quot; + i + &quot;].character&quot;);
    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 &lt; 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 &lt; nunAcc; i++) {  
  JsonCharacter jChar = new JsonCharacter();
  // Update jChar...
  itemList.add(jChar);
}

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:

确定