理解 Java 中的每个循环 [英] Understanding for each loop in Java

查看:13
本文介绍了理解 Java 中的每个循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码不符合我的预期.这段代码执行后,每个字符串都是空的.

The code below doesn't do what I expect. Every string is null after this code executes.

String[] currentState = new String[answer.length()];
for(String x : currentState)
{
    x = "_";
}

下面的代码符合我的预期.currentState 中的每个字符串现在都是_"

The code below does what I expect. Every string in currentState is now "_"

String[] currentState = new String[answer.length()];
for (int i = 0; i < currentState.length; i++) {
    currentState[i] = "_";
}

有人可以解释为什么第一种情况不起作用吗?

Can someone explain why the first case doesn't work?

推荐答案

通过设计每个变量 'x'(在本例中)并不是要分配给的.我很惊讶它甚至可以正常编译.

By design the for each variable 'x' (in this case) is not meant to be assigned to. I'm surprised that it even compiles fine.

String[] currentState = new String[answer.length()]; 
for (String x : currentState) { 
    x = "_"; // x is not a reference to some element of currentState 
}

以下代码可能显示了您实际上在做什么.请注意,这不是枚举的工作方式,但它举例说明了为什么不能分配x".它是位置i"处元素的副本.(请注意,该元素是一个引用类型,因此它是该引用的副本,对该副本的赋值不会更新相同的内存位置,即位置i"处的元素)

The following code maybe shows what you're in effect are doing. Note that this is not how enumerations work but it exemplifies why you can't assign 'x'. It's a copy of the element at location 'i'. ( note that the element is a reference type, as such it's a copy of that reference, assignment to that copy does not update the same memory location i.e. the element at location 'i')

String[] currentState = new String[answer.length()]; 
for (int i = 0; i < answer.length(); i++) { 
    String x = currentState[i];
    x = "_";
}

这篇关于理解 Java 中的每个循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆