Reputation: 178
So I have the function
public Foo findVariable(Foo input)
that returns an object of type Foo. I want to take that object, and then modify it in findVariable
in after it has been returned. I've read that you can't pass by reference in Java, so is it possible to have:
public void func1() {
Foo o = new Foo();
Foo exp = findVariable(o);
Foo newExp = new Foo(somethingDifferent);
exp = newExp;
}
What I want is that the Foo object returned by findVariable is changed to the object newExp. Sorry if this is not possible, or is simple but I can't find it from the methods I've used searching. Thanks!
Upvotes: 0
Views: 173
Reputation: 13779
You can mutate the Foo
returned by findVariable
in func1
:
public void func1() {
Foo o = new Foo();
Foo exp = findVariable(o);
exp.setSomething(different);
}
But if you do:
List<Foo> foosHandedOutByMe = ...
public Foo findVariable(Foo foo) {
Foo f = new Foo();
foosHandedOutByMe.add(f);
return f;
}
and then call:
public void func1() {
Foo o = new Foo();
Foo exp = findVariable(o);
Foo newFoo = new Foo(SomethingDifferent);
exp = newFoo;
}
the foosHandedOutByMe
list will not have the newFoo
object.
Upvotes: 2