简体   繁体   English

Java增强了For循环-编辑原始数组值

[英]Java Enhanced For Loop - Editing Original Array Values

I'd like to know, in detail, how the Enhanced For Loop works in Java (assuming i do get how the basic usage of this loop is and how it works in general). 我想详细了解Enhanced For Loop在Java中的工作方式(假设我确实了解了此循环的基本用法以及它的一般工作方式)。

Given the following code: 给出以下代码:

String[] a = {"dog", "cat", "turtle"};

for (String s : a) {
  out.println("String: " + s);
  s = in.readLine("New String? ");
}

It doesn't actually modify the original list 'a'. 它实际上并没有修改原始列表“ a”。 Why not? 为什么不? How memory Management works? 内存管理如何工作? Isn't 's' a reference to the same memory cell of 'a[i]'? “ s”不是对“ a [i]”的相同存储单元的引用吗?

I read on the oracle documentation that enhanced for loops can't be used to remove elements from the original array, it makes sense. 我在oracle文档中读到,增强的for循环不能用于从原始数组中删除元素,这很有意义。 Is it the same for modifying values? 修改值是否一样?

Thanks in advance 提前致谢

Isn't 's' a reference to the same memory cell of 'a[i]'? “ s”不是对“ a [i]”的相同存储单元的引用吗?

Originally, yes. 原来是。 But then in.readLine produces a reference to a new String object, which you then use to overwrite s . 但是随后in.readLine生成对新String对象的引用,然后可以使用该对象覆盖s But only s is overwritten, not the underlying string, nor the reference in the array. 但是只覆盖s ,而不覆盖基础字符串或数组中的引用。

s is a local variable that points to the String instance. s是一个局部变量,它指向String实例。 It is not associated with a[i] , they just happen to have the same value initially. 它与a[i]没有关联,它们刚好刚好具有相同的值。

You can only write 你只能写

for (int i = 0; i < a.length; i++) {
  out.println("String: " + a[i]);
  a[i] = in.readLine("New String? ");
}

You can't use for-each loops to modify the original collection or array. 您不能使用for-each循环来修改原始集合或数组。

Think in s like an address to an object. 想想s像一个地址的对象。 The thing here is that s is pointing out to a certain value of the array when using the for loop. 这里的问题是,使用for循环时, s指向数组的某个值。 When you reassing s inside the loop is just happen that s points out to another value but the original value of the array is not modified as you are only changing the address s is pointing to. 当你reassing s内环路只是发生s点到另一个价值,但该阵列的原始值不会被修改为只更改地址 s指向。

String[] a = {"dog", "cat", "turtle"};

for (String s : a) {
  //s --> "dog"
  out.println("String: " + s);
  s = in.readLine("New String? ");
  //s --> the new string the user inputs
}

For every iteration String s initially references to corresponding String object in String a[]. 对于每次迭代,String最初都引用String a []中的相应String对象。 But it is then referenced to another String object that is returned by in.readLine(). 但是它随后被in.readLine()返回的另一个String对象引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM