Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Development for stleary#516 completed with rebased repository #524

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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());
}
}
}