I observed that ArrayList reflects the latest value but for String, it does not
//Initializing List and String
ArrayList<String> list = new ArrayList<String>();
list.add("Item1");
String name = "String1";
//Setting Attribute for both
session.setAttribute("mylist", list);
session.setAttribute("myname", name);
//getting attribute for both
out.println("<br> Printing intial valus <br>");
list = (ArrayList<String>)session.getAttribute("mylist");
for (String s:list){
out.println(s);
}
name = (String) session.getAttribute("myname");
out.println(name);
//updating the values for both
list.add("Item2");
name = "String2";
//Need to add session.setAttribute again for String
//for it to reflect updated value "String 2"
//session.setAttribute("myname", name);
//getting attribute value after the update
list = (ArrayList<String>)session.getAttribute("mylist");
name = (String) session.getAttribute("myname");
//printing the value for both again
out.println("<br><br><br> Prining updated values <br><br>");
for (String s:list){
out.println(s);
}
out.println(name);
The output of the below is
Printing intial valus
Item1 String1
Prining updated values
Item1 Item2 String1 Session 2
In the updated values part, shouldn't it print "String2", but for ArrayList it's printing "Item2" as well. If I manually add session.setAttribute("myname", name)
just after updating String name values then it prints "String2". But this session.setAttribute is not required for the ArrayList