【问题标题】:Reference to the iteration number in Java's foreach引用 Java 的 foreach 中的迭代次数
【发布时间】:2009-10-08 20:30:18
【问题描述】:

如何在foreach中引用数组的索引?

我的代码

String[] name = { "hello", "world" };
for ( int k : name[k] ) {
   --- cut ---
}

我希望 foreach 循环会

1. set k = 0 in first iteration so that name[0] works correctly
2. set k = 1 in the next iteration...

我收到错误消息

foreach 不适用于表达式类型

【问题讨论】:

  • 您能否提供更多信息说明您认为需要索引的原因?你真的在做一些与位置相关的事情,还是只是对数组中的每个字符串做一些事情?

标签: java arrays foreach


【解决方案1】:

这是因为使用foreach 语法时索引不可用。如果需要索引,则必须使用 传统 迭代:

for (int i =0; i < names.length; i++) {
   String name = names[i];
}

如果您不需要索引,标准的foreach就足够了:

for (String name : names) {
    //...
} 

编辑显然你可以使用计数器来获取索引,但是你有一个在循环范围之外可用的变量,我认为这是不可取的 p>

【讨论】:

  • 在你的第二段中,我认为你的意思是写 index 而不是 syntax
  • 第一个 for 循环不会使用非索引集合。
  • @Steve:是的......但问题是关于数组,而不是集合。
【解决方案2】:

唯一的办法就是用计数器跟踪自己。

int cnt = 0;
String[] names = new String[10];
for (String s : names) {
   ...do something...
   cnt++;
}

【讨论】:

  • 最佳答案。基本上,你不能,但创建自己的计数器没有问题。
  • 如果你想要一个计数器,使用普通的for循环不是更好吗?
  • @ColinD - 这是一个折腾,但我发现 foreach 循环通常更易于阅读。
  • @downvote - 想解释一下吗?用 FOREACH 循环显示我的另一种方式来跟踪索引,因为这是问题所在。
【解决方案3】:

不,你不能那样做。在增强的 for 语句中,您只能迭代 Iterable。你不能在里面做任何其他事情。

【讨论】:

    【解决方案4】:
        Integer index = null;
        String[] tokens = new String[] { "I", "Love", "You" };
        List<String> arrs = Arrays.asList(tokens);
        for (String arr : arrs) {
            index = arrs.indexOf(arr);
            System.out.println("Index of " + arr + " is: " + index);
        }
    

    【讨论】:

    • 现在尝试对数组中的重复项执行相同操作。
    • @MarkRotteveel 感谢您让我检查这个。使用 String[] tokens = new String[] { "I", "Love", "You", "You" }; 检查时得到以下输出输出:** ====== ** ** I 的索引是:0 ** ** 爱的索引是:1 ** ** 你的索引是:2 ** ** 你的索引是:2 ** 我需要检查确切的原因,但时间...添加另一个答案到这个线程。
    【解决方案5】:

    在您的示例中,应该像这样使用 foreach 循环(复数 names 是比 name 更好的名称数组名称):

    String[] names = { "hello", "world" };
    for ( String name : names ) {
       // do something with the name
    }
    

    【讨论】:

      【解决方案6】:

      您不需要计数器。做吧

      String[] name = { "hello", "world" };
      for ( String s : name ) {
         --- cut ---
         System.out.println(s);
         --- cut ---
      }
      

      哪个会输出

      hello
      world
      

      【讨论】:

        【解决方案7】:

        当数组包含重复项时,将数组转换为列表的索引准确性存在问题。对于时间安排,在使用增强的 for 循环 for 列表的基础上推荐此解决方案。

            String[] tokens = new String[] { "I", "Love", "You", "You" };
            for(int i=0; i<tokens.length; i++) {
                System.out.println("token at index "+i+" is: "+tokens[i]);
            }
        

        【讨论】:

          【解决方案8】:

          您错误地使用了 for each 循环。它会自动为您提供对正在迭代的每个元素的引用,并且需要索引。在这种情况下,正确的方法如下:

          String[] name = {"hello", "world"};
          for(String s : name){
              System.out.println(s);
          }
          

          如果您需要更灵活地访问可迭代对象的元素,可以直接使用迭代器。数组不提供迭代器,所以我在这里使用了 List。

          List<String> name = Arrays.asList(new String[]{"hello", "world"});
          
          for(Iterator<String> it = name.iterator(); it.hasNext();){
              String currentName = it.next();
              System.out.println(currentName);
              it.remove();
          }
          

          【讨论】:

            猜你喜欢
            • 2011-08-08
            • 2011-09-07
            • 2012-03-30
            • 2021-10-05
            • 2011-11-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多