Today, when I was working on a project, I found a strange problem. The Code is as follows:
Jsonobject J = new jsonobject (); List <jsonobject> List = new arraylist <jsonobject> (); J. put ("author", "1 yuqiaotech"); J. put ("title", "1 test title"); // click the page J. put ("content", "1 test asiuninasd"); J. put ("Digest", "1 Digest"); system. out. println ("json1:" + J); list. add (j); J. put ("author", "2 yuqiaotech"); J. put ("title", "2 test title"); // the content of the text message page. html tag J is supported. put ("content", "2 test asiuninasd"); J. put ("Digest", "2 Digest"); system. out. println ("json1:" + J); list. add (j); system. out. println ("list (0):" + list. get (0); system. out. println ("list (1):" + list. get (1 ));
The purpose of this Code is to put two JSON contents in the list. First, a new jsonobject object is created, the first content is put into the list, and then the jsonobject is added to the list; then re-put the jsonobject value. The previous value will be overwritten, and the new content will be put into the jsonobject, and then the jsonobject will be added to the list; as you can imagine, there should be two different JSON objects in the list. Print the result:
Strangely, the two in the list are the contents of json2, and the contents of json1 are gone.
To solve this problem, perform a test:
First, use list to save the basic type object variables:
List<Integer> intList = new ArrayList<Integer>(); int i = 1; intList.add(i); System.out.println(intList); i = 2; intList.add(i); System.out.println(intList);
The printed results are correct.
Still use the following jsonobject:
Jsonobject J = new jsonobject (); List <jsonobject> List = new arraylist <jsonobject> (); J. put ("author", "1 yuqiaotech"); J. put ("title", "1 test title"); // click the page J. put ("content", "1 test asiuninasd"); J. put ("Digest", "1 Digest"); system. out. println ("json1:" + J); list. add (j); system. out. println ("list:" + list); J. put ("title", "2 test title"); system. out. println ("list:" + list );
Print result:
Why?
This problem needs to be viewed from the Java storage structure. For basic data, it is directly stored in the stack. When a new object is added like a list, only the object reference is passed to the list. When the object pointed to by the reference changes, the content in the corresponding list changes accordingly.
In this case, two different jsonobject objects must be used for separate storage.
I am also careless.
Traps in the list. Add () method