java - how to make List of of mutable objects Immuatable -
hi asked interview question have list of objects in immutable class, class immuatable, can modified , how can prevent it. gave below solution.
public final class a{ final list<b> listofb; // b mutable public list<b> getlistofb(){ return collections.unmodifiablelist(this.listofb); } }
now says after getting getlistofb() can change 'b' instances , wanted me avoid also. said.
public list<b> getlistofb(){ list<b> ret; for(b b: this.listofb){ ret.add(b.clone()); // make deep copy of 'b' return list } return ret; }
the interviewer did not respond saying right or wrong.
this solution definately works. there better way of doing it, approach clumsy , requires additional memory.
ps: assume b cannot made immutable.
assuming b
interface or implementation of interface a
, wrap each element of listofb
using java.net.proxy
of b
or a
respectively, intercepts modifying calls throwing unsupportedoperationexception
instead.
more detailed, replace each item of listofb
java.net.proxy
wrapped instance, implementing a
. whenever fetches item of listofb
, obtain wrapped instance instead. whenever calls setter on such wrapped item, intercept call , throw unsupportedoperationexception
. hope have idea mean. it's collections.unmodifiablexxx()
does. if have knowledge of methods may modify state of item of listofb
, b
not have pojo
. make sure wrapper replaces modifying methods throwing exception.
Comments
Post a Comment