java - Why make a collection unmodifiable? -
i know how make collection unmodifiable in java dont understand need such method exist. can please explain example scenario want make collection unmodifiable?
thanks in advance
take @ scenario. there application creates 2 users, , wants notify them something. users name different peter should notification.
so have user.class:
public class user { private string name; private integer id; public user(final integer id, final string name) { this.id = id; this.name = name; } public string getname() { return name; } public integer getid() { return id; } }
the users stored in special holder class (containing map):
public class usersholder { private static map<integer, user> usersmap = new hashmap<integer, user>(); public static void adduser(final user user) { usersmap.put(user.getid(), user); } public static map<integer, user> getusersmap() { return usersmap; //return collections.unmodifiablemap(usersmap); } }
then have userscreator creates users , stores them in map:
public class userscreator { public static void createusers() { usersholder.adduser(new user(1, "peter")); system.out.println("created user " + usersholder.getusersmap().get(1).getname()); usersholder.adduser(new user(2, "paul")); system.out.println("created user " + usersholder.getusersmap().get(2).getname()); } public static void main(string[] args) { userscreator.createusers(); system.out.println("number of users before notification: " + usersholder.getusersmap().size()); new usersnotificator().notifyallusersbutpeters(usersholder.getusersmap()); system.out.println("number of users after notification: " + usersholder.getusersmap().size()); } }
and notificator notifies peters:
public class usersnotificator { public void notifyallusersbutpeters(final map<integer, user> map) { //we don't need peters, we'll remove them list; iterator<entry<integer, user>> iterator = map.entryset().iterator(); while (iterator.hasnext()) { if (iterator.next().getvalue().getname().equals("peter")) { iterator.remove(); } } //now can notify list; notifyusers(usersholder.getusersmap()); } private void notifyusers(map<integer, user> map) { (final user user : map.values()) system.out.println("notifyingusers: " + user.getname()); } }
now - notificator presented map , may modify it, does. doesn't know shouldn't modify it's global usersmap. in effect removes users name peter. it's own purposes, results visible every other class using usersholder.
the result follows:
created user peter created user paul number of users before notification: 2 notifyingusers: paul number of users after notification: 1
when returning unmodifiablemap in usersholder removal not possible. way create new map users notify, our usersholder safe.
this example bit big, sorry that, failed think of/create somehting shorter.
unmodifiable map helps keep classes immutable safe(as presented in example) in multithreaded enviroment.
Comments
Post a Comment