Skip to content

Commit

Permalink
Merge pull request #524 from viveksacademia4git/i516-JSONArray-Constr…
Browse files Browse the repository at this point in the history
…uctParam-InitCapacity

Development for #516 completed with rebased repository
  • Loading branch information
stleary committed Jun 12, 2020
2 parents 601114e + d088cf0 commit 9de9743
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/main/java/org/json/JSONArray.java
Expand Up @@ -205,6 +205,22 @@ public JSONArray(Object array) throws JSONException {
}
}

/**
* Construct a JSONArray with the specified initial capacity.
*
* @param initialCapacity
* the initial capacity of the JSONArray.
* @throws JSONException
* If the initial capacity is negative.
*/
public JSONArray(int initialCapacity) throws JSONException {
if (initialCapacity < 0) {
throw new JSONException(
"JSONArray initial capacity cannot be negative.");
}
this.myArrayList = new ArrayList<Object>(initialCapacity);
}

@Override
public Iterator<Object> iterator() {
return this.myArrayList.iterator();
Expand Down
21 changes: 21 additions & 0 deletions src/test/java/org/json/junit/JSONArrayTest.java
Expand Up @@ -26,6 +26,7 @@ of this software and associated documentation files (the "Software"), to deal

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

Expand Down Expand Up @@ -1119,4 +1120,24 @@ public void toList() {
assertTrue("Removing an entry should succeed", list.remove(2) != null);
assertTrue("List should have 2 elements", list.size() == 2);
}

/**
* Create a JSONArray with specified initial capacity.
* Expects an exception if the initial capacity is specified as a negative integer
*/
@Test
public void testJSONArrayInt() {
assertNotNull(new JSONArray(0));
assertNotNull(new JSONArray(5));
// Check Size -> Even though the capacity of the JSONArray can be specified using a positive
// integer but the length of JSONArray always reflects upon the items added into it.
assertEquals(0l, (long)new JSONArray(10).length());
try {
assertNotNull("Should throw an exception", new JSONArray(-1));
} catch (JSONException e) {
assertEquals("Expected an exception message",
"JSONArray initial capacity cannot be negative.",
e.getMessage());
}
}
}

0 comments on commit 9de9743

Please sign in to comment.