ranjith Gampa
ranjith Gampa

Reputation: 105

HashMap values getting replaced in all keys

I am creating a HashMap by putting the values one by one. When I printed the hashmap after each iteration, the resultant hashmap contains the same value for all the keys. I do not understand why this is happening. I have pasted the output below

HashMap (String,List(Object)) mRestrictions;

                for(int k = 0; k < jArr.length(); k++){

                    Log.d(TAG,"inner Key:- "+jArr.getString(k)+" Values:- "+jObj.get(jArr.getString(k)));

                        list.clear();
                        list.add(0,jObj.get(jArr.getString(k)));
                        //Log.d(TAG, "Existing List:- "+list);

                        mRestrictions.put(jArr.getString(k),list);
                        Log.d(TAG, "One by One Restrictions:- "+mRestrictions);

                }

Output:-

One by One Restrictions:- {profile_name=[Test1]}

One by One Restrictions:- {profile_name=[url], url=[url}

One by One Restrictions:- {profile_name=[0], action=[0], url=[0]}

One by One Restrictions:- {profile_name=[Certificate], action=[Certificate], authentication_type=[Certificate], url=[Certificate]}

One by One Restrictions:- {profile_name=[ranjith], authentication_type=[ranjith], username=[ranjith], action=[ranjith], url=[ranjith]}

Upvotes: 0

Views: 598

Answers (2)

Ahmed Amr
Ahmed Amr

Reputation: 589

Probably The Problem is that you are using the same List object inside the loop.

Try to move your declaration of List object (list variable) to be inside the loop instead of calling .clear.

You actually added the same object each time to all keys, as java passes objects by reference.

Upvotes: 3

Louis Wasserman
Louis Wasserman

Reputation: 198471

list.clear();
list.add(0,jObj.get(jArr.getString(k)));

This does not do what you think it does. Java passes references by value. This line clears the lists that were already put in everywhere else. The way you've written it, there is only one list that you've mapped all these keys to.

Instead you must create a new list every time. You cannot reuse the same list.

Upvotes: 3

Related Questions