Java:For-Each 循环和引用 [英] Java: For-Each loop and references

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

问题描述

我想知道以下循环是否创建了对象的副本,而不是给我一个引用.原因是,因为第一个例子没有分配我的数组对象,但第二个却有.

I am wondering if the following loop creates a copy of the object, rather than giving me a reference to it. The reason is, because the first example doesn't allocate my array objects, but the second does.

MyObject objects[] = new MyObject[6];
for (MyObject o: objects) {

    o = new MyObject();
}

MyObject objects[] = new MyObject[6];
for(int i = 0; i < objects.length; i++) {

    objects[i] = new MyObject();
}

推荐答案

Java 的工作方式与许多其他语言略有不同.o 在第一个示例中只是对对象的引用.

Java works a little bit different than many other languages. What o is in the first example is simply a reference to the object.

当你说 o = new MyObject() 时,它会创建一个 MyObject 类型的新对象并引用 o 到那个对象,而在 o 之前code> 引用了 objects[index].

When you say o = new MyObject(), it creates a new Object of type MyObject and references o to that object, whereas before o referenced objects[index].

也就是说,objects[index] 本身只是对内存中另一个对象的引用.所以为了将objects[index]设置为一个新的MyObject,你需要改变objects[index]指向的位置,这只能通过使用objects[index]来完成.

That is, objects[index] itself is just a reference to another object in memory. So in order to set objects[index] to a new MyObject, you need to change where objects[index] points to, which can only be done by using objects[index].

图像:(我糟糕的绘画技巧:D)

Image: (my terrible paint skills :D)

说明:这大致就是 Java 内存管理的工作原理.不完全是,无论如何,但大致上.您有引用 A1 的对象.访问对象数组时,从起始参考点 (A1) 开始,然后向前移动 X 个块.例如,引用索引 1 会将您带到 B1.然后 B1 告诉您您正在 A2 处寻找对象.A2 告诉您它有一个位于 C2 的字段.C2 是一个整数,一种基本数据类型.搜索完成.

Explanation: This is roughly how Java memory management works. Not exactly, by any means, but roughly. You have objects, which references A1. When you access the objects array, you start from the beginning reference point (A1), and move forward X blocks. For example, referencing index 1 would bring you to B1. B1 then tells you that you're looking for the object at A2. A2 tells you that it has a field located at C2. C2 is an integer, a basic data type. The search is done.

o 不引用 A1 或 B1,而是引用 C1 或 C2.当您说 new ... 时,它会创建一个新对象并将 o 放在那里(例如,在插槽 A3 中).不会影响A1或B1.

o does not reference A1 or B1, but C1 or C2. When you say new ..., it will create a new object and put o there (for example, in slot A3). It will not affect A1 or B1.

如果我能把事情弄清楚一点,请告诉我.

Let me know if I can clear things up a little.

这篇关于Java:For-Each 循环和引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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