How to return the values from an array within a certain range.
java - Fill arrays with ranges of numbers - Stack Overflow
Range in Array Java - Stack Overflow
Get only part of an Array in Java? - Stack Overflow
I have a method that is asking me to return all the values within a range and put them into a new array. So...{4, 5, 6, 7, 8} with a range of 5 to 7 would become a new array of {5, 6, 7}. Hopefully that makes sense. I looked into the copyOfRange method but that uses the indexes and I need to use the given numbers from the range. I don't have the actual range numbers so I have to write a method that can account for any given range. Thanks in advance.
For those still looking for a solution:
In Java 8 or later, this can be answered trivially using Streams without any loops or additional libraries.
int[] range = IntStream.rangeClosed(1, 10).toArray();
This will produce an array with the integers from 1 to 10.
A more general solution that produces the same result is below. This can be made to produce any sequence by modifying the unary operator.
int[] range = IntStream.iterate(1, n -> n + 1).limit(10).toArray();
Another useful and not widely known Java 8 solution for existing arrays:
int[] array = new int[10];
Arrays.setAll(array, i -> i + 1);
The length of an array in Java is immutable. So, you need to copy the desired part into a new array.
Use copyOfRange method from java.util.Arrays class:
int[] newArray = Arrays.copyOfRange(oldArray, startIndex, endIndex);
startIndex is the initial index of the range to be copied, inclusive.
endIndex is the final index of the range to be copied, exclusive. (This index may lie outside the array)
E.g.:
//index 0 1 2 3 4
int[] arr = {10, 20, 30, 40, 50};
Arrays.copyOfRange(arr, 0, 2); // returns {10, 20}
Arrays.copyOfRange(arr, 1, 4); // returns {20, 30, 40}
Arrays.copyOfRange(arr, 2, arr.length); // returns {30, 40, 50} (length = 5)
You could wrap your array as a list, and request a sublist of it.
MyClass[] array = ...;
List<MyClass> subArray = Arrays.asList(array).subList(index, array.length);