i’m having an issue where I would like the below code to add the specified elements from the first array to the new array at the given indexes. However, the problem is that the loop with not exit.
For eg. The below should print items at index 4 and 5 and then exit as the array only has items indexed up to 5. However it is printing “the”, “mat” followed by “null” and “null”.
Any tips would be appreciated. It has the pass the following tests, which the below advice does not. ”’ @Test public void _2c_pagedData_reflection() throws Exception {
String[] data = {"the", "cat", "sat", "on", "the", "mat"}; { final String[] expected2n2 = {"sat", "on"}; final String[] result = tester.executeStatic(String[].class, "pagedData", data, 2, 2); assertArrayEquals(expected2n2, result); } { final String[] expected4n4 = {"the", "mat"}; final String[] result = tester.executeStatic(String[].class, "pagedData", data, 4, 4); assertArrayEquals(expected4n4, result); } { final String[] expected2n3 = {"sat", "on", "the"}; final String[] result = tester.executeStatic(String[].class, "pagedData", data, 2, 3); assertArrayEquals(expected2n3, result); } }'''
‘
package com.company; public class Main { public static void main(String[] args) { String[] data = {"the", "cat", "sat", "on", "the", "mat"}; String[] lol = pagedData(data, 4, 4); for (int i = 0; i < lol.length; i++) { System.out.println(lol[i]); } } static String[] pagedData(String[] array, int startIndex, int maxSize) { String[] newArray = new String[maxSize]; int count = 1; for (int i = 0; i < newArray.length; i++) { if (startIndex < array.length) { String index = array[startIndex]; newArray[i] = index; startIndex++; count++; } } return newArray; } }
Advertisement
Answer
You are instantiating a array of length maxSize
(i.e. 4) even though it is only going to copy 2 elements into that array – so the other 2 elements are null. Calculate the size of the returned array from the array.length
and startIndex
and then limit this by maxSize
. Use System.arrayCopy()
to copy arrays.
static String[] pagedData(String[] array, int startIndex, int maxSize) { int length = array.length - startIndex; if (length > maxSize) { length = maxSize; } String[] slice = new String[length]; System.arrayCopy(array, startIndex, slice, 0, length); return slice; }
Edit: adding a sample JUnit test
@Test public void testSlice() { String[] array = {"the","cat","sat","on","the","mat"}; int startIndex = 4; int maxSize = 4; String[] expected = {"the","mat"}; String[] actual = Testing.pagedData(array, startIndex, maxSize); Assert.assertArrayEquals(expected, actual); }