Does Java have an equivalent to Python's range(int, int)
method?
views:
82answers:
4
+1
A:
public int[] range(int start, int length) {
int[] range = new int[length - start + 1];
for (int i = start; i <= length; i++) {
range[i - start] = i;
}
return range;
}
(Long answer just to say "No")
Vivien Barousse
2010-09-24 19:10:58
Also, see that "range" in python 3 and the preferred "xrange" in Python 2 return a "live" object that does not use up memory for each item it contains. That would be even bigger to implement in Java.
jsbueno
2010-09-25 00:58:57
+1
A:
Nothing built-in, but Googling reveals ways to add it. Here are a couple (a serious bug is noted in the first one, however): http://snippets.dzone.com/posts/show/3792
kindall
2010-09-24 19:11:00
+1
A:
public int[] range(int start, int stop)
{
int[] result = new int[stop-start];
for(int i=0;i<stop-start;i++)
result[i] = start+i;
return result;
}
Forgive any syntax or style errors; I normally program in C#.
KeithS
2010-09-24 19:12:29
given that Vivien Barousse beat you to an answer, why don't you delete yours to avoid any dup. Unless you really plan to nicely flesh it out of course.
aaronasterling
2010-09-24 19:24:06
They're similar; I think mine's a little more readable. His use of "length" is misleading, and I don't think his meets the Python spec (he includes the upper bound, which http://www.network-theory.co.uk/docs/pytut/rangeFunction.html says doesn't happen in Python). If you think one's a dupe, I believe you have sufficient reputation to deal with it yourself.
KeithS
2010-09-24 20:06:55
A:
If you mean to use it like you would in a Python loop, Java loops nicely with the for statement, which renders this structure unnecessary for that purpose.
Nikki9696
2010-09-24 19:12:31