Asa*_*saf 7 java foreach primitive-types
我不禁想知道为什么我不能写那样的东西:
for (int i : 3) {
System.out.println(i);
}
Run Code Online (Sandbox Code Playgroud)
打印出来:
0
1
2
Run Code Online (Sandbox Code Playgroud)
我的意思是,3可以自动装箱Integer,也可以Iterable.
我知道,我已经选择了第一个元素0,但我认为这是常见的情况,并且它可以利用这样的ForEach构造来促进倒计时.
Mat*_*mes 10
这有点愚蠢,但你可以这样写:
for (int i : iter(3)) {
System.out.println(i); // 0, 1, 2
}
for (int i : iter(-5)) {
System.out.println(i); // 0, -1, -2, -3, -4
}
for (int i : iter(1, 7)) {
System.out.println(i); // 1, 2, 3, 4, 5, 6
}
Run Code Online (Sandbox Code Playgroud)
如果您要静态导入方法:
import static your.package.IterUtil.iter;
Run Code Online (Sandbox Code Playgroud)
来自这个自定义类:
public class IterUtil {
public static Iterable<Integer> iter(int to) {
return new IntIterable(0, to);
}
public static Iterable<Integer> iter(int from, int to) {
return new IntIterable(from, to);
}
private static class IntIterable implements Iterable<Integer> {
private int start;
private int end;
private IntIterable(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private int actual = start;
@Override
public boolean hasNext() {
return actual != end;
}
@Override
public Integer next() {
int value = actual;
if (actual < end) {
actual++;
} else if (actual > end) {
actual--;
}
return value;
}
@Override
public void remove() {
// do nothing
}
};
}
}
}
Run Code Online (Sandbox Code Playgroud)
因为数字不是范围.将数字转换为范围是不明确的.没有什么从编写范围类,阻止你是迭代的,例如
public class IntegerRange implements Iterable<Integer> {
private final int _fromInclusive;
private final int _toExclusive;
public IntegerRange(int fromInclusive, int toExclusive) {
_fromInclusive = fromInclusive;
_toExclusive = toExclusive;
}
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
int c = _fromInclusive;
public boolean hasNext() {
return c < _toExclusive;
}
public Integer next() {
if (c >= _toExclusive) {
throw new NoSuchElementException();
}
return c++;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,通过这种方法,您可以轻松添加诸如指定增量,范围是否包含两侧等功能.
| 归档时间: |
|
| 查看次数: |
1962 次 |
| 最近记录: |