Skip to content

Commit ae77b5c

Browse files
committed
Tests for deep copy and mutability of toList() and toMap().
Both toMap() and toList() return deep copies, which are also mutable. That is, any changes to the JSONObject or JSONArray do not affect the newly create Map or List, and vice-versa. The resulting objects can be altered.
1 parent 72c2b91 commit ae77b5c

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

src/test/java/org/json/junit/JSONArrayTest.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -920,5 +920,13 @@ public void toList() {
920920
assertTrue("val3 list val 2 should not be null", val3Val2List != null);
921921
assertTrue("val3 list val 2 should have 1 element", val3Val2List.size() == 1);
922922
assertTrue("val3 list val 2 list element 1 should be null", val3Val2List.get(0) == null);
923+
924+
// assert that toList() is a deep copy
925+
jsonArray.getJSONObject(1).put("key1", "still val1");
926+
assertTrue("val2 map key 1 should be val1", val2Map.get("key1").equals("val1"));
927+
928+
// assert that the new list is mutable
929+
assertTrue("Removing an entry should succeed", list.remove(2) != null);
930+
assertTrue("List should have 2 elements", list.size() == 2);
923931
}
924932
}

src/test/java/org/json/junit/JSONObjectTest.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2141,5 +2141,14 @@ public void toMap() {
21412141
assertTrue("key3 list val 2 should not be null", key3Val2List != null);
21422142
assertTrue("key3 list val 2 should have 1 element", key3Val2List.size() == 1);
21432143
assertTrue("key3 list val 2 list element 1 should be null", key3Val2List.get(0) == null);
2144+
2145+
// Assert that toMap() is a deep copy
2146+
jsonObject.getJSONArray("key3").getJSONArray(0).put(0, "still value 1");
2147+
assertTrue("key3 list val 1 list element 1 should be value1", key3Val1List.get(0).equals("value1"));
2148+
2149+
// assert that the new map is mutable
2150+
assertTrue("Removing a key should succeed", map.remove("key3") != null);
2151+
assertTrue("Map should have 2 elements", map.size() == 2);
2152+
21442153
}
21452154
}

0 commit comments

Comments
 (0)