开发者

print range of integers in descending or ascending order in java

开发者 https://www.devze.com 2022-12-19 17:00 出处:网络
I have an upper bound and a lower bound and I want to return all numbe开发者_C百科r number betweenthe bounds including the bounds. I know python has a range function but I\'m sure if java has this met

I have an upper bound and a lower bound and I want to return all numbe开发者_C百科r number between the bounds including the bounds. I know python has a range function but I'm sure if java has this method.


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.


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


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;
    }
  };
}
0

精彩评论

暂无评论...
验证码 换一张
取 消