[英]Why is this loop prematurely exiting when removing JSON objects?
我有一个简单的 JSON 数组。
{
"food" : [
{
"name" : "apple"
},
{
"name" : "orange"
},
{
"name" : "peach"
},
{
"name" : "carrot"
},
{
"name" : "lettuce"
}
]
}
但是当我尝试删除所有但保留一个时,删除 for 循环先发制人地退出。
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();
或带有remove()
的Iterator
Iterator<JsonValue.ValueType> iter = list.iterator();
while (iter.hasNext()) {
JsonValue.ValueType value = iter.next();
println("removed: " + value);
iter.remove();
}
请注意链接的 Javadoc 中的注释:如果在迭代正在进行时以调用此方法以外的任何方式修改了底层集合,则迭代器的行为是未指定的。
感谢接受的答案,我意识到我的问题就像在开始循环之前捕获项目数量一样简单。
if (found >= 0) { // found at index 3.
int countOfItemsToRemove = list.length(); // do this
println("number of items before removeall loop: " + countOfItemsToRemove); // prints 5.
for (int i = 0; i < countOfItemsToRemove; ++i) {
println("removed item: " + i); // prints 0, 1, 2.
list.remove(i);
}
println("adding item: " + addThisItemBack); // {"food":["name":"carrot"}]}
list.put(addThisItemBack);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.