PHP range function in Java

The PHP range function works like this: php:

$leap_years = range(1900, 2000, 4); 

creates an array like 1900, 1904, 1908, ... Is there anything simple in Java?

+4
source share
3 answers

There is nothing built-in for this, but it is relatively simple to implement a range such as an immutable Iterable<Long> (or Integer or something else). Just create a custom Iterator that starts with an initial value, and then increment for each call to next() until you pass the final value. You have to decide how and if you want to handle high iterative iteration and so on, but it’s not difficult. You can also do this as an immutable List implementation, where the value for each index is calculated on demand ( start + index * increment ).

While your question relates to creating a range-based β€œarray”, an array full of data in the entire range is often not needed, especially if you just want to iterate over the numbers in the range. If that's all you need, you end up repeating the numbers in the range twice to create an array or List , and then read it. Using the lazy range iterator, as I described, does not have this drawback. In addition, a lazy iterator can be easily copied to a List if you want all values ​​to be stored directly in memory. The only drawback to this compared to building an array is some of the official duties.

+4
source

You should do it as follows:

 public int[] range(int start, int end, int increment) { if (start < end && increment < 0) throw new IllegalArgumentException(); if (start > end && increment > 0) throw new IllegalArgumentException(); int[] values = new int[Math.abs((end - start) / increment) + 1]; boolean reverse = start > end; for (int i = start, index = 0; reverse ? (i >= end) : (i <= end); i+=increment, ++index) { values[index] = i; } return values; } 
+3
source

You could mimic this as follows:

 public int[] range(int startVal, int endVal, int increment) { if (startVal >= endVal) { //handle error or add option to go backwards } int count = ((endval - startval) / increment) + 1; int[] myArr = new int[count]; for (int i=0; i <= count; i++) { myArr[i] = startVal + (i * increment); } return myArr; } } 
+1
source

All Articles