views:

460

answers:

3

I have an upper bound and a lower bound and I want to return all number number between the bounds including the bounds. I know python has a range function but I'm sure if java has this method.

A: 

You can just use a for loop. Do you want to print them or return them? Your title and question disagree on this. If you want to return them, you will need to pick the type that you use to contain them.

List<Integer> ret = new ArrayList<Integer>();
for (int i = lower; i <= upper; i++) {
    ret.add(i);
}
return ret;

I will leave it as an exercise to print them, or to get them in descending order.

danben
sorry for the misunderstanding, i wanted to print them. But I know how to do that: System.out.print(i + " ");Thanks for the help mate! :D
Dan
+1  A: 

If you have an array if integers you can use IntRange in Apache Commons Lang:

http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/math/IntRange.html

IntRange ir = new IntRange(int lower, int upper);
ir.toString();

More info of the various Range's you can use here:

http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/math/class-use/Range.html

Jon
A: 

EDIT: I totally over-read the question. I saw a suggestion of an IntRange utility and I just assumed this was the classic "I want an Iterable" request, which I hear often. So ignore the below.

Simplified (without error checking):

public static List<Integer> range(final int start, final int end) {
  return new AbstractList<Integer>() {
    public int size() {
      return end - start + 1;
    }
    public Integer get(int i) {
      return start + i;
    }
  };
}
Kevin Bourrillion