1

I have a function like this:

public static int partition(List list, ListElement elemL, ListElement elemR){
    ListElement elemX;
    ...
    elemR = elemX.next;
    return x; 
}

And at the end of the funktion the elemR is changed, but after calling the function from the main method the parameter elemR has still the same value like before the function call. What's the problem? How can i change this ListElement and "save" this change after the function is called without changing the return type to ListElement (i need the integer return value too)?

hp58
  • 135
  • 1
  • 3
  • 10
  • Java isn't call by reference it is only call by value. Take a look at [this](http://stackoverflow.com/questions/40480/is-java-pass-by-reference) – FDinoff May 12 '13 at 23:53
  • what do you mean with "make the method destructive"? how to do that? – hp58 May 12 '13 at 23:54
  • 1
    This example may help you http://stackoverflow.com/questions/5607773/change-a-functions-arguments-values – Marek May 12 '13 at 23:56
  • Ok, I think I understand the problem But I still have no idea how to fix this problem, because I'm note able to change the value of elemX, I have to allocate another object to elemR. Does anybody have an idea, how to do this? – hp58 May 13 '13 at 00:06
  • OK, I think I just found a solution. I put the elemR and elemL in a ArrayList and put the ArrayList as parameter in the function, so it seems to work successful (: – hp58 May 13 '13 at 00:18

1 Answers1

9

Java functions parameters are called by reference name, meaning that when you place an object as an function argument, the JVM copies the reference's value to a new variable, and passes it to the function as an argument. If you change the contents of the object, then the original object will change, but if you change the actual value of the reference, then these changes will be destroyed when the function ends.

I hope it helps

boring32
  • 136
  • 4