tags:

views:

82

answers:

4

Does Java have an equivalent to Python's range(int, int) method?

+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
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
+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
+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
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
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
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
You don't usually use it for a loop in python either. There's almost always a cleaner way to iterate.
Daenyth
Well, range is usually used in a for loop. But for loops are often used without range.
FogleBird