Albert.Qing
Albert.Qing

Reputation: 4625

Strange thing in ArrayList

I have a mArraylist object,the Strange things happens after mArraylist add(object); here is my source.why is aj1 equals aj2 in arraylist.It make me crazy! what's wrong?

          /*get a mArraylist*/
           ArrayList<JSONObject> ajson;
           /*get an object that to be add.*/
        JSONObject jsonObject = new JSONObject();
    /*check result*/
        ArrayList<JSONObject> aj1 = new ArrayList<JSONObject>();
        aj1 = ajson;
        int size_outter = ajson.size();


        ArrayList<JSONObject> aj2 = new ArrayList<JSONObject>();
        ajson.add(jsonObject);
        aj2 = ajson;
        int size_inner = ajson.size();

    /*check aj1,aj2,eqauls*/
        if (aj1.equals(aj2))
        {
            System.out.println("aj1.equals(aj2)======true==");
        }

        System.out.println("aj1=ajson============size" + size_outter);
        System.out.println("aj2=ajson============size" + size_inner);

        System.out.println("aj1=============size" + aj1.size());
        System.out.println("aj2=============size" + aj2.size());



//the output is 
11-26 12:40:37.885: INFO/System.out(7214): aj1.equals(aj2)======true==
11-26 12:40:37.885: INFO/System.out(7214): aj1=ajson============size0
11-26 12:40:37.885: INFO/System.out(7214): aj2=ajson============size1
11-26 12:40:37.885: INFO/System.out(7214): aj1=============size1
11-26 12:40:37.885: INFO/System.out(7214): aj2=============size1

why aj1 equals aj2? but its size is not?

Upvotes: 1

Views: 86

Answers (2)

gwvatieri
gwvatieri

Reputation: 5183

aj1 and aj2 are 2 references to the same object (ajson), you did that when these 2 lines:

aj1 = ajson;
...
aj2 = ajson;

as matter of the fact the size is the same:

11-26 12:40:37.885: INFO/System.out(7214): aj1=============size1
11-26 12:40:37.885: INFO/System.out(7214): aj2=============size1

With this line:

if (aj1.equals(aj2))

you are comparing the same object.

Upvotes: 1

kabuko
kabuko

Reputation: 36312

aj1 is pointing to the exact same object as aj2. The sizes are equal. The problem is that you're storing the size, then adding an item, then storing the size again. So you've recorded the size of the same object at two different times, and in between you've added an item. So of course the sizes will be different.

Upvotes: 1

Related Questions