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

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

问题描述

下面的代码没有做我期望的。在这段代码执行后,每个字符串都是空的。

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

$ / code $ / pre

下面的代码是我所期望的。 currentState中的每个字符串现在都是_

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





$ b

有人可以解释为什么第一个案例不起作用吗?

解决方案

通过设计,每个变量x(在这种情况下)并不意味着分配给。我很惊讶,它甚至编译好。

  String [] currentState = new String [answer.length()]; 
for(String x:currentState){
x =_; // x不是对currentState的某个元素的引用

code $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $显示你正在做的事情。请注意,这不是枚举的工作方式,但它举例说明了为什么不能分配'x'。这是位置我的元素的副本。 (编辑:请注意,该元素是一个引用类型,因此它是该引用的副本,分配给该副本不会更新相同的内存位置,即位置'我'的元素)

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


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 = "_";
}

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?

解决方案

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 
}

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'. (Edit: 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天全站免登陆