I know his very old thread. However, the approved answer itself did not help me. And here is how I resolved it.
Create a method like this:
String[] sliceArray(String[] arrayToSlice, int startIndex, int endIndex) throws ArrayIndexOutOfBoundsException { if (startIndex < 0) throw new ArrayIndexOutOfBoundsException("Wrong startIndex = " + startIndex); if (endIndex >= arrayToSlice.length) throw new ArrayIndexOutOfBoundsException("Wrong endIndex = " + endIndex); if (startIndex > endIndex) { // Then swap them! int x = startIndex; startIndex = endIndex; endIndex = x; } ArrayList<String> newArr = new ArrayList<>(); Collections.addAll(newArr, arrayToSlice); for (int i = 0; i < arrayToSlice.length; i++) { if (!(i >= startIndex && i <= endIndex)) // If not with in the start & end indices, remove the index newArr.remove(i); } return newArr.toArray(new String[newArr.size()]); }
Then it is called like this:
String lines[] = {"One", "Two", "Three", "Four", "Five"}; lines = sliceArray(lines, 0, 3);
This will lead to:
"One", "Two", "Three", "Four"
Now I can slice the array in any way I want!
lines = sliceArray(lines, 2, 3);
This will lead to:
"Three", "Four"
Dilip muthukurussimana
source share