简体   繁体   中英

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;

}

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.

No, org.codehaus.jettison.json.JSONArray is not immutable.

When you do jsonArray = ja1 , the original object remains unchanged and only the local reference in the myMethod scope is updated.

To make changes in the object passed, you can either invoke methods upon the reference passed or return a modified object.

String jsonArrayAsString;
JSONArray ja = new JSONArray(jsonArrayAsString)
myMethod(ja);
// ja now contains new object element

ja = myMethod1(ja);
// ja now points to a new JSONArray containing an elements from the original array with another additional element

public void myMethod(JSONArray jsonArray){
   jsonArray.put(object); // this will add object to the original JSONArray
}

public JSONArray myMethod1(JSONArray jsonArray){
    JSONArray a = new JSONArray();
    a.put(jsonArray.get(0));
    a.put(object);
    return a;
}

PS: Please go through the link mentioned in another answer which shows how references work in Java.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM