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

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

问题描述

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

  MyObject objects [] =新的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();

$ / code $ / $ p

解决方案

Java的工作有点不同比许多其他语言。在第一个例子中, o 仅仅是对象的引用。



当你说 o = new MyObject(),它创建一个新的MyObject对象,并引用 o 到该对象,而 o 引用 objects [index]



也就是说,objects [index ]本身只是对内存中另一个对象的引用。因此,为了将对象[索引]设置为一个新的MyObject,您需要更改对象[index]指向的位置,只能使用对象[index]完成。


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

o不引用A1或B1,但引用C1或C2。当你说 new ... 时,它会创建一个新的对象并把它放在那里(例如在A3槽中)。它不会影响A1或B1。



让我知道我是否可以稍微清理一下。


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 works a little bit different than many other languages. What o is in the first example is simply a reference to the object.

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

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

Image: (my terrible paint skills :D)

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 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天全站免登陆