How can I assign an object to another object when I only have a reference to it in Java?

I use Java and have various objects that I make as a list:

objx   o1;
objx   o2;
objx   o3;

objx olist [] = { o1, o2, o3 };

now I want to assign other objects to the original o1-o3 objects, but using a list.

Sort of:

olist[0] = onew;

But in this case, only the list is changed, and not the original object o1. How to do it in Java?

+3
source share
3 answers

You can not. However, you can just save the array, and then you can change the object referenced at each place in the array.

eg.

objx olist[] = new objx[ 3 ];

olist[ 0 ] = new objx( );
olist[ 1 ] = new objx( );
olist[ 2 ] = new objx( );

Then you can change any of the referenced objects by simply specifying an array:

...

olist[ 1 ] = onew;
+1
source

. o1 - - , o1 , .

"" o1 , (, ) .

+3

You must use container objects. That is, an object containing a reference to the objx object. The simplest container object will be an array of one element, but it is an extremely ugly and error prone solution.

Note that for brevity, I did not use access methods. Usually you should not use direct member access, as here.

public class ObjxContainer {
    public Objx objx;
}

...

ObjxContainer o1;
ObjxContainer o2;
ObjxContainer o3;
ObjxContainer[] arr = new ObjxContainer[] { o1, o2, o3 };

Now access to objx in ObjxContainer will have the desired effect:

arr[0].objx = new Objx();
-1
source

All Articles