0

I am trying to manipulate an object inside a method like this:

My class Problem:

public class TaxiProblem {

public Problem(final World world, final Agent agent) {
        _world = world;
        _world.setRandomAgent(_agentPlace);
    }

private Place _agentPlace;

// Various other functions

}

and in the function .setRandomAgent() in the class World I am trying to manipulate the Place object in what I want it to be like this:

public void setRandomAgent(Place agentPlace) {
        int rand = _random.nextInt(25);
        agentPlace = _places.get(rand);
        agentPlace.setHasAgent(true);
    }

I basically want to grab a random Place from the List _places and have it in the variable agentPlace in .setRandomAgent() which in turn will have it in _agentPlace in the Problem class. I thought this would work since Java passes objects by reference in methods but it didn't and _agentPlace remains null.

  • 1
    Java passes parameters by value, not by reference. http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – Pete May 01 '14 at 15:20

3 Answers3

2

By doing this

agentPlace = _places.get(rand);

you are overwriting the reference that was passed to the method and losing access to the object you want to alter.

In your setRandomAgent method, agentPlace is indeed a reference that points to your _agentPlace field, not the field itself. In the line I pasted above, what you do is make that reference point to a different object.

cangrejo
  • 2,139
  • 2
  • 21
  • 31
1
_agentPlace = _world.getRandomAgent();


public Place getRandomAgent() {
        int rand = _random.nextInt(25);
        Place agentPlace = _places.get(rand);
        agentPlace.setHasAgent(true);
        return agentPlace();
    }

When you pass agentPlace to the method, you are creating a copy of the reference. So if you modify the object, then it would work when you return up the stack. But reassigning the variable makes you lose the object you were working with.

0

I suspect that your problem lies in the implementations as your understanding of pass by reference I believe is correct. The following code will produce the results you expect - That is, it will first print "Before change", then "I am changed!".

class Program
{
    static void Main(string[] args)
    {
        var problem = new Problem();
    }
}


public class Problem
{
    public Problem()
    {
        var toChange = new ClassToChange();
        toChange.ChangeMe = "Before change";
        Console.WriteLine(toChange.ChangeMe);

        var changer = new ClassThatChanges();
        changer.ChangeSomething(toChange);
        Console.WriteLine(toChange.ChangeMe);

        Console.ReadLine();
    }
}

public class ClassToChange
{
    public string ChangeMe { get; set; }
}

public class ClassThatChanges
{
    public void ChangeSomething(ClassToChange classToChange)
    {
        classToChange.ChangeMe = "I am changed!";
    }
}