Search code examples
javajsonjettison

Is org.codehaus.jettison.json.JSONArray Immutable?


I pass org.codehaus.jettison.json.JSONArray as an argument to a method and I update (add/remove elements from the array) it in the method.

But the changes are not reflecting in the caller. From the source code, the class doesn't seem to Immutable. I am doing something as below in terms of code.

String jsonArrayAsString;
JSONArray ja = new JSONArray(jsonArrayAsString)
myMethod(ja);
// ja here remains unchanged

public void myMethod(JSONArray jsonArray){
   JSONArray ja1 = JSONArray();
   jsonArray = ja1;

}

Solution

  • You're not mutating the jsonArray object passed as an argument. What you're doing in this code snippet is changing the value of a reference.

    Within the body of myMethod, jsonArray is initially a reference to the object passed as an argument. In the second line of the method you change this reference to point at the newly constructed object ja1.

    See Is Java "pass-by-reference" or "pass-by-value"? and this tutorial on method/constructor arguments.

    In order to change the object you pass to myMethod, you need to change its state by calling a method, setting a property, etc.