Question

I'm working in some Java code and I have a doubt. I have a loop that goes along a Collection to modify each one of its objects with a method. The thing is, when you pass an object to a method, what are you really passing? A copy of the reference? the memory address? Here is my code:

for(Iterator it = colDesglosesBDI.iterator(); it.hasNext();)
{    
    DesgloseBDIVO desgloseBDI = (DesgloseBDIVO)it.next();
    desgloseBDI = completeDesgloseAgrup(desgloseBDI);
}

The method completeDesgloseAgrup returns a DesgloseBDIVO Object so I can replace the old objects with the new attributes. But maybe I can do it by this way:

for(Iterator it = colDesglosesBDI.iterator(); it.hasNext();)
{    
    DesgloseBDIVO desgloseBDI = (DesgloseBDIVO)it.next();
    completeDesgloseAgrup(desgloseBDI);
}

And in this case the method would be void and do not return any object. Is possible to do it in that way?

Regards

Was it helpful?

Solution

Yes that is entirely possible provided the completeDesgloseAgrup() method only changes the attributes of the argument, and does not try to replace it with a new object.

Consider this:

public void completeDesgloseAgrup( DesgloseBDIVO d )
{
    // will work, callee will see "something"
    d.setSomething( "something" );
}

public void completeDesgloseAgrup( DesgloseBDIVO d )
{
    // Won't work, as Java has call by value semantics. Callee won't see the new DesgloseBDIVO in callee's scope.
    d = new DesgloseBDIVO()
    d.setSomething( "something" );
}

Cheers,

OTHER TIPS

In java objects are data structures on the heap which you reference by variables, hence you never pass the objects, always the reference to an object.

From "The Java Programming Language, 4th edition" by Ken Arnold, James Gosling and David Holmes:

The Java programming language does not pass objects by reference; it passes object references by value. Because two copies of the same reference refer to the same actual object, changes made through one reference variable are visible through the other. There is exactly one parameter passing mode pass by value and that helps keep things simple.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top