简体   繁体   中英

How does session work in java?

If I put a map in session. Then if I remove an object from map. Will this also change the map in session or do I have to put the map in session again?

            Map map = new HashMap();

        map.put("1", "1");
        map.put("2", "2");
        map.put("3", "3");
        map.put("4", "4");

        Session session = getSession();

        session.setAttribute("myMap", map);

        map.remove("1");

Yes it will update map in the session......

 Map map = new HashMap();
        map.put("1", "1");
        map.put("2", "2");
        map.put("3", "3");
        map.put("4", "4");
        session.setAttribute("myMap", map);

        map.remove("1");
        Object mapw = session.getAttribute("myMap");  
        out.println(mapw);

Output

{3=3, 2=2, 4=4}

The session keeps a reference to the object that you put in. If you change the content of the map, the map object reference doesn't change. It's still the same map, so the info you have in the session will also change.

Like so:

Map original_map = new HashMap();
session.setAttribute("myMap", original_map);

// Now put something into original_map...
// The _content_ of the map changes

// Later:
Map retrieved_map = session.getAttribute("myMap");

// you'll find that retreived_map == original_map.
// They're the same object, the same Map reference.
// So the retrieved_map contains all that you put into the original_map.

Your map still remains in the session. However, could be a better practice to use a WeakHashMap in this case. See the below link

Weak Hash Map Discussion

Yes, it will update.

The reason behind this is all objects in Java are passed by reference unless of course the accessor returns a copy of the object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM