Search code examples
javacall-by-value

Modifying object collections


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


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,