Java for(int i : x) 有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29588837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:15:57  来源:igfitidea点击:

What does for(int i : x) do?

javafor-loop

提问by ksraj98

I am new to Java. I was reading someone's solution to a question and I encountered this:

我是 Java 新手。我正在阅读某人对一个问题的解决方案,我遇到了这个:

        int[] ps = new int[N];
        for (int i = 0; i < N; i++)
            ps[i] = input.nextInt();

        int[] counts = new int[1005];
        for (int p : ps)
            counts[p]++;

What do the last two lines do?

最后两行有什么作用?

采纳答案by user253751

This is a for-each loop. It sets pto the first element of ps, then runs the loop body. Then it sets pto the second element of ps, then runs the loop body. And so on.

这是一个for-each 循环。它设置p为 的第一个元素ps,然后运行循环体。然后它设置p为 的第二个元素ps,然后运行循环体。等等。

It's approximately short for:

它大约是以下内容的缩写:

for(int k = 0; k < ps.length; k++)
{
    int p = ps[k];
    counts[p]++;
}

回答by Crazyjavahacking

That's a for loop. for (int p : ps)iterates over ints in the psint array

那是一个for循环。for (int p : ps)迭代psint 数组中的整数

回答by silentprogrammer

The line is iterating over each index of array an taking out its value in a sequence in a pvarable.You can check by

该行迭代数组的每个索引,并在变量的序列中取出其值。p您可以通过

for (int p : ps){            // if ps is {1,2,3}
   System.out.print(p+" ");  // it will print 1 2 3
   counts[p]++;
}

回答by Neeraj Jain

For-each loop (Advanced or Enhanced For loop):

For-each 循环(高级或增强型 For 循环):

The for-each loop introduced in Java5. It is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable.

Java5 中引入的 for-each 循环。主要用于遍历数组或集合元素。for-each 循环的优点是它消除了错误的可能性并使代码更具可读性。

Syntax

句法

for(data_type variable : array | collection){}  

Source :Java For Each Loop

来源:Java For Each Loop

In your case this loop is iterating the Array

在您的情况下,此循环正在迭代 Array

Equivalent Code without For Each Loop

不带 For Each 循环的等效代码

for (int i=0;i<ps.length;i++){
int p=ps[i];
counts[p]++;
}