Skip to content

Commit

Permalink
Development for #516 completed with rebased repository
Browse files Browse the repository at this point in the history
- Introduced JSONObject(int) constructor.
   - int > Initial capacity of the underlying data structure

- Test for new introduced JSONArray(int) constructor.
   1. Checked with input parameter: 0
   2. Checked with input parameter: positive number
   3. Checked with positive number input parameter and compared length
   4. If input parameter is negative number JSONException is thrown:
         JSONArray initial capacity cannot be negative.
  • Loading branch information
viveksacademia4git committed Jun 3, 2020
1 parent 19bb6fd commit d088cf0
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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 d088cf0

Please sign in to comment.