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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There isn’t anything built in for this, but it’s relatively simple to implement such a range as an immutable
Iterable<Long>(orIntegeror whatever). Just create a customIteratorthat starts at the start value and then increment for each call tonext()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 ofListwhere 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
Listand 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 aListif 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.