了解Java中的每个循环

下面的代码没有达到我的预期。 执行此代码后,每个字符串都为null。

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

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

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

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

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

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

以下代码可能会显示您正在执行的操作。 请注意,这不是枚举的工作原理,但它举例说明了为什么不能指定’x’。 它是位于’i’的元素的副本。 (编辑:请注意,元素是引用类型,因此它是该引用的副本,对该副本的赋值不会更新相同的内存位置,即位置“i”处的元素)

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

原始代码:

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

重写代码:

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

我将如何编写代码:

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

用错误重写代码:

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

当你做这样的事情时,使变量成为最终亮点(这是一个常见的初学者错误)。 尝试使所有变量成为最终的(实例,类,参数,catch中的exception等等) - 如果你真的需要改变它们,只能使它们成为非最终变量。 您应该会发现90%-95%的变量是最终的(初学者在开始这样做时最终会有20%-50%)。

因为x是引用(或引用类型的变量 )。 所有第一段代码都是将引用重新指向一个新值。 例如

 String y = "Jim"; String x = y; y = "Bob"; System.out.println(x); //prints Jim System.out.println(y); //prints Bob 

您将引用y重新分配给“Bob”的事实不会影响引用x分配。

您可以将数组转换为List,然后像这样迭代:

 String[] currentState = new String[answer.length()]; List list = Arrays.asList(currentState); for(String string : list) { x = "_"; } 

对象x [] = {1,“ram”,30000f,35,“account”}; for(Object i:x)System.out.println(i); for each用于顺序访问

for each循环意味着:

 List suits = ...; List ranks = ...; List sortedDeck = new ArrayList(); for (Suit suit : suits){ for (Rank rank : ranks) sortedDeck.add(new Card(suit, rank)); } 

所以考虑一下你可以这样做:

 String[] currentState = new String[answer.length()]; List buffList = new ArrayList<>(); for (String x : currentState){ x = "_"; buffList.add(x); // buffList.add(x = "_" ); will be work too } currentState = buffList.toArray(currentState);