Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP's range function in Java

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?

like image 866
Centurion Avatar asked Feb 26 '23 23:02

Centurion


1 Answers

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.

like image 190
ColinD Avatar answered Mar 08 '23 06:03

ColinD