NonCreature0714 :
I have a simple JSON array.
{
"food" : [
{
"name" : "apple"
},
{
"name" : "orange"
},
{
"name" : "peach"
},
{
"name" : "carrot"
},
{
"name" : "lettuce"
}
]
}
But when I try to remove all but keep one, the removal for-loop pre-emptively exits.
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);
}
But this results in:
{
"food" : [
{
"name" : "carrot"
},
{
"name" : "lettuce"
}
]
}
Instead of:
{
"food" : [
{
"name" : "carrot"
}
]
}
How can I make sure the list is completely emptied before I add an item back? Did I overlook something obvious? Is this something esoteric to JSON manipulation?
Elliott Frisch :
Every time you remove an element, the list
shrinks. This
for (int i = 0; i < list.length(); ++i) {
println("removed item: " + i); // prints 0, 1, 2.
list.remove(i);
}
Means i
quickly passes the length of the list
. I would suggest List.clear()
like
list.clear();
or an Iterator
with remove()
Iterator<JsonValue.ValueType> iter = list.iterator();
while (iter.hasNext()) {
JsonValue.ValueType value = iter.next();
println("removed: " + value);
iter.remove();
}
Be aware of the note from the linked Javadoc: The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.