使用最终变量实现循环
答
是递归允许的,或者你从字面上需要一个循环构造像for
或while
?如果你可以使用递归的话:
void loop(final int n) {
if (n == 0) {
return;
} else {
System.out.println("Count: " + n);
loop(n-1);
}
}
+0
这很有趣:) – 2013-03-21 18:40:51
答
事情是这样的 -
final int max = 5;
for(int i=0; i<max; i++) {}
或者另一个有趣的单
final boolean flag = true;
while(flag) {
// keep doing your stuff and break after certain point
}
一个更多 -
List<String> list = ......
for(final Iterator iterator = list.iterator(); iterator.hasNext();) {
}
+0
不确定'i'或'flag'是否不制动规则“初始化后你不允许改变任何东西” – Pshemo 2013-03-21 18:37:26
答
创建一个数组,其大小为所需的迭代次数,然后在for-each循环使用它:
public class Test {
public static void main(String[] args) {
final int N = 20;
final int[] control = new int[N];
for(final int i : control){
System.out.println(i);
}
}
}
这里的诀窍是,迭代索引由编译器生成,作为增强for语句的一部分,不使用任何用户声明的变量。
答
的一种方式是创建表示任意范围的Iterable<Integer>
类(而实际上不必所有的值存储在一个列表):
public static class FixedIntRange implements Iterable<Integer> {
private final int min;
private final int max;
public FixedIntRange(final int min, final int max) {
this.min = min;
this.max = max;
}
@Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private Integer next = FixedIntRange.this.min;
@Override
public boolean hasNext() {
return next != null;
}
@Override
public Integer next() {
final Integer ret = next;
next = ret == max ? null : next + 1;
return ret;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
,然后遍历其通常:
for (final int i : new FixedIntRange(-10, 20)) {
// this will be run for each i in the range [-10, 20]
}
你的问题不清楚... – assylias 2013-03-21 18:37:17
哎呀,它可能是那么容易,因为'的(最终的AtomicInteger I =新的AtomicInteger(0); i.get()
yshavit
2013-03-21 19:15:04