简体   繁体   English

Java增强了for循环

[英]Java enhanced enhanced for loop

Currently (as of Java 6), using Java's enhanced for-loop I do not know of any way to directly access the iterator index short of reverting to the old indexed for-loop or using an outside counter. 目前(从Java 6开始),使用Java的增强型for循环我不知道有什么方法可以直接访问迭代器索引,而不是恢复到旧的索引for循环或使用外部计数器。

Are there plans (or perhaps a current way) to implement this "enhanced enhanced" for-loop where one would be able to access the index of the loop (and even possibly manipulate it)? 有没有计划(或者当前的方法)来实现这个“增强的增强”for循环,其中一个人能够访问循环的索引(甚至可能操纵它)?

As an example where this might be needed, consider(this is from actual production code): 作为可能需要这样做的示例,请考虑(这是来自实际的生产代码):

int i = 1;
for (final String action : actions) {
  parameters.set(String.valueOf(i++), action);
}

Well, like you said, if you must have an index just use a standard for loop, or update a counter manually. 好吧,就像你说的,如果你必须有索引只需使用标准for循环,或手动更新计数器。

But rethink your question. 但重新考虑你的问题。 Why should you need an index in a for (Object o : list) loop? 为什么在for (Object o : list)循环中需要索引?

The whole point of using an enhanced loop is to abstract away the nasty parts of using an index or an iterator. 使用增强循环的整点是抽象掉使用索引或迭代器的肮脏部分。

Most languages today do not give this kind of functionality in loops. 今天的大多数语言都没有在循环中提供这种功能。 Just as an example, the Pythonic way to do this is: 举个例子,Pythonic的方法是:

for index, val in enumerate(someList):
    # ....

不。使用外部变量。

Why would they need to provide yet another way of accessing elements by index? 为什么他们需要提供另一种通过索引访问元素的方法?

The enhanced for loop was created as a shortcut for when you don't need the index of the element. 当您不需要元素的索引时,会创建增强的for循环作为快捷方式。 It streamlined things. 它精简了一切。

If you still need the index, fall back to a regular for loop. 如果仍然需要索引,则回退到常规for循环。 That's one of the reasons they're there. 这是他们在那里的原因之一。

It's better to keep an outside counter to get the index,but you could do something like this ( it's bit of an overkill for a simple task) : 最好保留一个外部计数器来获取索引,但是你可以做这样的事情(这对于一个简单的任务来说有点过分)

class Enum<T> implements Iterable<Indexer<T>> {
    private int indx;
    private Iterator<T> itr;
    private Indexer<T> indxr = new Indexer<T>();

    private Enum(Iterable<T> iter) {
        this.itr = iter.iterator();
    }

    public static <T> Enum<T> iterate(Iterable<T> iter) {
        return new Enum<T>(iter);
    }

    @Override
    public Iterator<Indexer<T>> iterator() {
        return new AbstractIterator<Indexer<T>>() {
            @Override
            protected Indexer<T> computeNext() {
                if (itr.hasNext()) {
                    indxr.index = indx++;
                    indxr.val = itr.next();
                    return indxr;
                }
                return endOfData();
            }

        };
    }

}

class Indexer<T> {
    public int index;
    public T val;

    @Override
    public String toString() {
        return String.format("[ %d : %s ]", index, val);
    }

For getting index while while iterating: 在迭代时获取索引:

    List<Integer> list = new ArrayList<Integer>() ;
    list.addAll(Arrays.asList(1, 2, 3, 4, 5,6,55,23,12,24,16));
    for (Indexer<Integer> en : Enum.iterate(list)) 
      System.out.println(en.index+" "+en.val);

Note:The above code has dependency to Guava's AbstractIterator 注意:上面的代码依赖于Guava的 AbstractIterator

There isn't way right now unless you keep a counter! 除非你保留一个柜台,否则现在没有办法! I know this is ugly, but java 7 will be better. 我知道这很难看,但java 7会更好。 I don't know why other people are saying we don't need it. 我不知道为什么其他人说我们不需要它。 Sometimes we need to know what is last member, or odd member, etc. 有时我们需要知道什么是最后一个成员,或奇数成员等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM