I am looping through a JSONArray. names
and amount
are ArrayList <String>
JSONArray data = json.getJSONArray("data");
int i = 0;
for (i = 0; i < data.length(); ++i) {
JSONObject rec = data.getJSONObject(i);
String name = rec.getString("name");
names.add(i, name);
String amount_v = rec.getString("amount");
amount.add(i, amount_v);
Log.v(logtag, i + " - " + names.size());
}
Log.v(logtag, "final - " + names.size());
For every value of i, names.size() is twice that of i even though I am adding only one element inside the loop. data has 5 records with name and amount as two columns. But after the loop, names contain all 10 values (5 names and 5 amounts). But actually, only 5 names should have been added to names list.
What I see in the log..
0 - 2
1 - 4
2 - 6
3 - 8
4 - 10
final - 10
Why does it add the value of amount_v
into the names list?
因为这两个称为amount
和names
引用引用了相同的ArrayList实例。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.