@@ -154,7 +154,7 @@ public JSONArray(String source) throws JSONException {
154
154
* A Collection.
155
155
*/
156
156
public JSONArray (Collection <?> collection ) {
157
- this .myArrayList = new ArrayList <Object >();
157
+ this .myArrayList = new ArrayList <Object >(collection == null ? 0 : collection . size () );
158
158
if (collection != null ) {
159
159
for (Object o : collection ){
160
160
this .myArrayList .add (JSONObject .wrap (o ));
@@ -172,6 +172,7 @@ public JSONArray(Object array) throws JSONException {
172
172
this ();
173
173
if (array .getClass ().isArray ()) {
174
174
int length = Array .getLength (array );
175
+ this .myArrayList .ensureCapacity (length );
175
176
for (int i = 0 ; i < length ; i += 1 ) {
176
177
this .put (JSONObject .wrap (Array .get (array , i )));
177
178
}
@@ -495,7 +496,7 @@ public int length() {
495
496
* Get the optional object value associated with an index.
496
497
*
497
498
* @param index
498
- * The index must be between 0 and length() - 1.
499
+ * The index must be between 0 and length() - 1. If not, null is returned.
499
500
* @return An object value, or null if there is no object at that index.
500
501
*/
501
502
public Object opt (int index ) {
@@ -1150,7 +1151,13 @@ public JSONArray put(int index, Object value) throws JSONException {
1150
1151
}
1151
1152
if (index < this .length ()) {
1152
1153
this .myArrayList .set (index , value );
1154
+ } else if (index == this .length ()){
1155
+ // simple append
1156
+ this .put (value );
1153
1157
} else {
1158
+ // if we are inserting past the length, we want to grow the array all at once
1159
+ // instead of incrementally.
1160
+ this .myArrayList .ensureCapacity (index + 1 );
1154
1161
while (index != this .length ()) {
1155
1162
this .put (JSONObject .NULL );
1156
1163
}
@@ -1302,7 +1309,7 @@ public JSONObject toJSONObject(JSONArray names) throws JSONException {
1302
1309
if (names == null || names .length () == 0 || this .length () == 0 ) {
1303
1310
return null ;
1304
1311
}
1305
- JSONObject jo = new JSONObject ();
1312
+ JSONObject jo = new JSONObject (names . length () );
1306
1313
for (int i = 0 ; i < names .length (); i += 1 ) {
1307
1314
jo .put (names .getString (i ), this .opt (i ));
1308
1315
}
0 commit comments