JSONオブジェクトを削除するときに、なぜこのループが途中で終了していますか?

NonCreature0714:

私は、単純なJSON配列を持っています。

{
  "food" : [
    {
      "name" : "apple"
    },
    {
      "name" : "orange"
    },
    {
      "name" : "peach"
    },
    {
      "name" : "carrot"
    },
    {
      "name" : "lettuce"
    }
  ]
}

しかし、私はすべてを削除しようとするが、1つを維持する場合、除去のためのループ事前emptively終了します。

String itemToKeepsName = "carrot";
JSONArray list = wrappedFood.getJSONArray("food");
JSONObject addThisItemBack = null; // be ready to make a new space in memory.

println("number of items in list: " + list.length()); // prints 5.
int found = -1;
for(int i = 0; i < list.length(); ++i) {
  if(addThisItemBack.equals(list.getJSONObject(i).getString("name"))) {
    found = i;
    addThisItemBack = new JSONObject(list.getJSONObject(i).toString());
  }
}

if (found >= 0) { // found at index 3.
  println("number of items before removeall loop: " + list.length()); // prints 5.
  for (int i = 0; i < list.length(); ++i) {
    println("removed item: " + i); // prints 0, 1, 2. 
        list.remove(i);
  }

  println("adding item: " + addThisItemBack); // {"food":["name":"carrot"}]}
  list.put(addThisItemBack);

}

しかし、この結果には:

{
  "food" : [
    {
      "name" : "carrot"
    },
    {
      "name" : "lettuce"
    }
  ]
}

の代わりに:

{
  "food" : [
    {
      "name" : "carrot"
    }
  ]
}

どのように私は、アイテムバックを追加する前に、必ずリストが完全に空にされていることを確認することができますか?私は何かを明らかに見逃していましたか?これは、JSONの操作に難解なものですか?

エリオットの新鮮:

あなたは要素を削除するたびに、list収縮。この

for (int i = 0; i < list.length(); ++i) {
    println("removed item: " + i); // prints 0, 1, 2. 
    list.remove(i);
}

手段は、i迅速の長さを渡しますlist私は示唆しているList.clear()ような

list.clear();

またはIteratorremove()

Iterator<JsonValue.ValueType> iter = list.iterator();
while (iter.hasNext()) {
    JsonValue.ValueType value = iter.next();
    println("removed: " + value);
    iter.remove();
}

リンクのJavadocからノートに注意してください:反復がこのメソッドを呼び出すこと以外の方法で進行中に、基になるコレクションが変更された場合、反復子の動作は不定です。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=18795&siteId=1
おすすめ