Utils { @NonNull static JSONArray subArray(@NonNull JSONArray arr, int fromIndex, int toIndex) { if (fromIndex > toIndex) { throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } JSONArray jsonArray = new JSONArray(); try { for (int i = fromIndex; i < toIndex; i++) { jsonArray.put(arr.getJSONObject(i)); } } catch (JSONException e) { e.printStackTrace(); } return jsonArray; }    }
@Test public void testSubArray() { final JSONArray geofenceArray = GeofenceJSON.getGeofenceArray(); JSONArray expectedSubArrayFirst = GeofenceJSON.getFirstFromGeofenceArray(); JSONArray actualSubArrayFirst = Utils.subArray(geofenceArray, 0, 1); try { JSONAssert.assertEquals(expectedSubArrayFirst, actualSubArrayFirst, true); } catch (JSONException e) { e.printStackTrace(); } JSONArray expectedSubArrayFull = geofenceArray; JSONArray actualSubArrayFull = Utils.subArray(geofenceArray, 0, expectedSubArrayFull.length()); try { JSONAssert.assertEquals(expectedSubArrayFull, actualSubArrayFull, true); } catch (JSONException e) { e.printStackTrace(); } JSONArray expectedSubArrayLast = GeofenceJSON.getLastFromGeofenceArray(); JSONArray actualSubArrayLast = Utils.subArray(geofenceArray, 1, geofenceArray.length()); try { JSONAssert.assertEquals(expectedSubArrayLast, actualSubArrayLast, true); } catch (JSONException e) { e.printStackTrace(); } Assert.assertThrows("IllegalArgumentException must be thrown when fromIndex is greater than lastIndex", IllegalArgumentException.class, new ThrowingRunnable() { @Override public void run() throws Throwable { Utils.subArray(geofenceArray, geofenceArray.length(), 0); } }); }