转载

java – Foreach vs common for loop

我刚刚开始学习 Java

,我遇到的第一件事是foreach循环,不知道它的工作方式我做的第一件事是:

int[] array = new int [10];
for (int i: array){
    i = 1;
}

并且显然未能为数组的每个元素分配1.然后我添加了System.out.print(i); (在i = 1之后;)到循环的主体并且看到屏幕的输出是1111111111但是因为在循环内部用i做某事是有效的,我很可能是数组的每个元素的副本,ain’是吗? (第一个问题)

如果上述情况属实,这并不意味着foreach循环比公共for循环要慢得多,因为它涉及制作数组中每个元素的副本?或者由于Java没有指针和指针算术,oprator []可能会以其他一些“糟糕”的方式设计,复制每个元素实际上更快?

如果上述假设为真,为什么人们会使用明显较慢的foreach循环而不是常见的forloop?

简而言之:

>我是数组中每个元素的副本吗?如果不是它的话

然后?

> foreach循环不是常见的慢吗?如果没有,怎么样

那么“糟糕”是操作符[]的设计?

>除了在foreach循环中获胜的可读性之外没有其他内容了吗?

在代码中

for (int i: array){

您声明一个变量i,在每个循环迭代中获取数组中下一个元素的值,它不是对该元素的引用.

i = 1;

您为变量赋值,而不是为数组中的元素赋值.

您不能直接使用foreach循环设置数组元素的值.为此使用正常for循环

for (int i = 0; i < array.length; i++) {
    array[i] = ...; // some value
}

在上面的示例中,您使用声明的变量i作为数组中元素的索引.

array[i]

正在访问元素本身,您可以修改其值.

Ans obviously failed to assign 1 to every element of the array. The I  added System.out.print(i); to the body of the loop and saw that the  output of the screen was 1111111111 but since doing something with i  inside the loop is valid that most likely i is a copy of every element  of the array, ain’t it? (first questions)

您必须在i = 1之后放置System.out.print(i),否则您将获得0000000.

If the above is true doesn’t this mean that the foreach loop is much  slower then the common for loop since it involves making copies of  each element of the array? Or since Java doesn’t have pointers and  pointer arithmetic, the oprator[] may be designed in some other  “badly” fashion that copying every element is actually faster?

看看 here ,看看foreach循环是如何工作的.对于阵列,

for (int i: array){
    i = 1;
}

相当于

for (int index = 0; index < array.length; index++) {
    int i = array[index];
    i = 1;
}

所以它并不慢.你正在堆栈上做一个更原始的创建.

这取决于实施.对于数组,它不会以任何方式变慢.它只是用于不同的目的.

why one would use an obviously slower foreach loop instead of a common  forloop?

一个原因是可读性.另一种是当你不关心更改数组的元素引用时,而是使用当前引用.

以参考类型为例

public class Foo {
    public int a;
}

Foo[] array = new Foo[3];
for (int i = 0; i < array.length; i++) {
    array[i] = new Foo();
    array[i].a = i * 17;
}

for (Foo foo : array) {
    foo.a = 0; // sets the value of `a` in each Foo object
    foo = new Foo(); // create new Foo object, but doesn't replace the one in the array
}

对于原始类型,这样的东西不起作用.

for (int index = 0; index < array.length; index++) { 
    int i = array[index];
    i = 1; // doesn't change array[index]
}

翻译自:https://stackoverflow.com/questions/18788316/foreach-vs-common-for-loop

原文  https://codeday.me/bug/20190111/518217.html
正文到此结束
Loading...