Java Enhanced For Loop - 编辑原始数组值 [英] Java Enhanced For Loop - Editing Original Array Values

查看:304
本文介绍了Java Enhanced For Loop - 编辑原始数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想详细了解Enhanced For循环如何在Java中工作(假设我知道这个循环的基本用法,以及它如何工作)。



给出以下代码:

$ p $ String [] a = { 狗,猫,乌龟};

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

它实际上并不修改原始列表a。
为什么不呢?内存管理如何工作?是不是对a [i]的同一个存储单元的引用?

我在oracle文档上看到,增强for循环不能用于从原始数组中删除元素,这是有道理的。修改值是否相同?

提前致谢

解决方案


是不是引用了'a [i]'的同一个内存单元?

原来是的。但是, in.readLine 会生成一个新的String对象的引用,然后用它来覆盖 s 。但是只有 s 被覆盖,而不是基础字符串,也不是数组中的引用。


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).

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'. Why not? How memory Management works? Isn't 's' a reference to the same memory cell of '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. Is it the same for modifying values?

Thanks in advance

解决方案

Isn't 's' a reference to the same memory cell of 'a[i]'?

Originally, yes. But then in.readLine produces a reference to a new String object, which you then use to overwrite s. But only s is overwritten, not the underlying string, nor the reference in the array.

这篇关于Java Enhanced For Loop - 编辑原始数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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