PHP's range function work like this in php :
$leap_years = range(1900, 2000, 4);
creates array like 1900, 1904, 1908, ...
Is there something simple like this in Java?
There isn't anything built in for this, but it's relatively simple to implement such a range as an immutable Iterable<Long>
(or Integer
or whatever). Just create a custom Iterator
that starts at the start value and then increment for each call to next()
until you pass the end value. You have to decide how and if you want to handle high-to-low iteration and such as well, but it isn't hard. You could also do this as an unmodifiable implementation of List
where the value for each index is calculated on demand (start + index * increment
).
While your question refers to the creation of an "array" based on the range, an array full of the data on the whole range is often not needed, particularly if you just want to iterate through the numbers in the range. If that's all you want, you'll end up iterating through the numbers in the range twice to create an array or List
and then read it. Using a lazy range iterator as I've described doesn't have this disadvantage. Additionally, a lazy iterator can easily be copied into a List
if you do want all the values stored in memory directly. The only disadvantage of it in comparison to building an array is some autoboxing overhead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With