开发者

List.addAll is replicating session variables

开发者 https://www.devze.com 2023-01-25 14:05 出处:网络
I have the following code in my action class: MemberData mbr = MyUtil.getMember(request.getSession());

I have the following code in my action class:

MemberData mbr = MyUtil.getMember(request.getSession());
:::::::::::::::::::::::
{
 List sysList = mbr .getSystemList();   //returns 'systemList'
 sysList.addAll(mbr .getUserEnteredList());  //add user entered to the system entered objects list
 addWorksheetFor(wb, sysList);  //add the list to an excel workbook
}

I have the MemberData in the s开发者_C百科ession and it contains a list called, say, systemList. When I am using List sysList = mbr.getSystemList() and then adding user entered list, the 'systemList' in the session object gets modified. I am adding the two list into a local variable 'sysList' but the session variable 'systemList' is also modified. It becomes the same as 'sysList'.

However, when I iterate through the systemList and userEnteredList separately and add to a third list like the following:

MemberData mbr = MyUtil.getMember(request.getSession());
:::::::::::::::::::::::
{
 List sysList = mbr .getSystemList();   //returns 'systemList'
 List userList = mbr .getUserEnteredList();  //returns 'userEnteredList'
 List allList = new ArrayList();
 for (Iterator it=sysList.iterator(); it.hasNext();)
 allList.add(it.next());
 for (Iterator it=userList.iterator(); it.hasNext();
 allList.add(it.next());
 addWorksheetFor(wb, sysList);  //add the list to an excel workbook
}

Then it works. The session variable do not get modified in this case. Any ideas?


List sysList = mbr .getSystemList();

If you are directly returning the list instance variable in MemberData both sysList and MemberData.sysList will be the same list. So any changes to one of them will be reflected in the other.

To solve this you need to create a new List somewhere in your code, best place is probably the getter in MemberData.


Java doesn't return a copy of the value (instance) when you obtain a reference as you seem to expect. It returns exactly the same value (instance). That's called pass-by-value and is indeed confusing for programmers who have a procedural programming language background (e.g. PHP).

Your best bet is to just create a new value (instance). The way as you attempted is however a bit clumsy and can be simplified as follows:

List sysList = mbr.getSystemList();   // returns 'systemList'
List userList = mbr.getUserEnteredList();  // returns 'userEnteredList'
List allList = new ArrayList(sysList); // creates a copy of 'sysList'
allList.addAll(userList); // adds 'userList' to copy of 'sysList'


Number 6 in http://www.javacoffeebreak.com/articles/toptenerrors.html explains why your code snippets work the way they do.

0

精彩评论

暂无评论...
验证码 换一张
取 消