Java增强for循环中获取index [b]前提测试数据:[/b]
String[] data = new String[]{"rensanning001", "rensanning002", "rensanning003"};
List<String> dataList = Arrays.asList(data);
[b]普通的For循环:[/b]
for (int i = 0; i < dataList.size(); i++) {
System.out.println(i + ":" + (i));
}
[b]增强For循环(获取index需要定义额外的变量):[/b]
int i = 0;
for (String elem : dataList) {
System.out.println(i + ":" + elem);
i++;
}
[b]⾃定义静态⽅法实现带index的循环:[/b]
for (Indexer<String> elem : ExtFor1.loop(dataList)) {
System.out.println(elem.index() + ":" + elem.value());
}
public class ExtFor1 {
public static <T> Iterable<Indexer<T>> loop(final Iterable<T> list) { return new Iterable<Indexer<T>>() {
@Override
public Iterator<Indexer<T>> iterator() {
return new Iterator<Indexer<T>>() {
private int counter = 0;
private Iterator<T> iterator = list.iterator();
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Indexer<T> next() {
Indexer<T> elem = new Indexer<T>(counter++, ()); return elem;
}
@Override
public void remove() {
throw new RuntimeException();
}
};
}
};
}
}
[b]扩展Iterable实现带index的循环:[/b]
for (Indexer<String> elem : ExtFor2.loop(dataList)) {
System.out.println(elem.index() + ":" + elem.value());
}
public class ExtFor2<T> implements Iterable<Indexer<T>> {
private Iterator<T> iterator;
private ExtFor2(Iterable<T> iter) {
this.iterator = iter.iterator();
}
public static <T> ExtFor2<T> loop(Iterable<T> iter) {
return new ExtFor2<T>(iter);
}
@Override
public Iterator<Indexer<T>> iterator() {
return new Iterator<Indexer<T>>() {
private int counter = 0;
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Indexer<T> next() {
Indexer<T> elem = new Indexer<T>(counter++, ()); return elem;
}
@Override
public void remove() {
throw new RuntimeException();
}
};
}
}
[b]jquery风格的for循环:[/b]
For.each(dataList, new For.Function<String>() {
public void execute(int index, String elem) {
System.out.println(index + ":" + elem);
}
});
public class For {
public static <T> void each(List<T> list, Function<T> function) { int length = list.size();
for (int index = 0; index < length; index++) {
}
}
public static interface Function<T> {
java中index是什么意思public void execute(int index, T obj);
}
}
public class Indexer<T> {
private final int index;
private final T value;
public Indexer(int index, T value) {
this.index = index;
this.value = value;
}
public int index() {
return this.index;
}
public T value() {
return this.value;
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论