| Author |
Unable to understand the setAttribute in java
|
kee sihbagnis
Greenhorn
Joined: Sep 15, 2011
Posts: 2
|
|
Hi there-Good Wishes to all, am a beginner here and i got stuck at a servlet code and i am just wondering how does compiler proceeds in this case , so here goes the code:
Assumptions-Am entering into it for 1st time hence products=null.
Now products, being null, will now be set to->products=new ArrayList(); AND "hs.setAttribute("products",products);" will be set.
My Question is-Since we have set the Attribute-products in line-12 now if i make any change in products[like in line number 28] will the change be reflected on Attribute-products if i happen to use it in another servlet.
For eg.In line-12 Atrribute-product is null and in line-28 i have added 3 items to products NOW if i use getAttribute("products") in another servlet will it be null or it will show the 3 added items.
What i think is- once an Attribute is set then whatever changes we make to that particular Attribute shouldn't get reflected unless we set that Attribute again with updated value but it is going the other way around and i am confused.
Entire code is here-webpage
Extremely sorry if i overlooked the solution in code itself and wasted your time.
|
 |
N Sahni
Ranch Hand
Joined: Jul 07, 2011
Posts: 55
|
|
Hi,
In java whenever you set/put or pass any object. It is the copy of the reference that gets stored.
Hence, when you modify any value on that reference it gets reflected when you actually get that attribute.
|
Thanks and Regards,
Nilesh Sahni | nsahni@infocepts.com | www.infocepts.com
|
 |
kee sihbagnis
Greenhorn
Joined: Sep 15, 2011
Posts: 2
|
|
Nilesh,
Thank you very very much for your prompt and clear reply, you made my day,my doubt is clear now
Thanks again
|
 |
N Sahni
Ranch Hand
Joined: Jul 07, 2011
Posts: 55
|
|
Welcome
|
 |
jeya velan
Greenhorn
Joined: Feb 07, 2011
Posts: 9
|
|
Good response..
I ran the following JSP to check this.
The output is:
[one, two, three, four]
null
In the code above even after changing the arrayList point to null, the list in the session displays four values.
But if we call the setter again the value in the session changes to null.
Changes done on the reference reflects in the list stored in the session.
But changing the reference to null not reflecting.
I don't know why.Can you help.
Thanks in advance.
|
 |
Bear Bibeault
Author and ninkuma
Marshal
Joined: Jan 10, 2002
Posts: 56168
|
|
|
Changing the reference does not change the object.
|
[Smart Questions] [JSP FAQ] [Books by Bear] [Bear's FrontMan] [About Bear]
|
 |
 |
|
|
subject: Unable to understand the setAttribute in java
|
|
|