Path: csiph.com!usenet.pasdenom.info!aioe.org!.POSTED!not-for-mail From: Roedy Green Newsgroups: comp.lang.java.programmer Subject: Re: String[] , Arrays.asList , Collections.unmodifiableList Date: Fri, 09 May 2014 09:25:26 -0700 Organization: Canadian Mind Products Lines: 38 Message-ID: <8a0qm9dovj2i2pn1ltfvt0cd8gitlpapbv@4ax.com> References: Reply-To: Roedy Green NNTP-Posting-Host: K2Qzzs3EAqXk5RLzfhxcSw.user.speranza.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit X-Complaints-To: abuse@aioe.org User-Agent: ForteAgent/7.20.32.1218 X-Notice: Filtered by postfilter v. 0.8.2 Xref: csiph.com comp.lang.java.programmer:28417 On Fri, 09 May 2014 01:02:35 -0500, leif.roar@invalid.com (Leif Roar Moldskred) wrote, quoted or indirectly quoted someone who said : >Roedy Green wrote: >> >> So what do people do? They use Arrays.asList to convert to a List, an >> java.util.Arrays$ArrayList. > >Return a clone of the internal array, not the array itself: > >public class NotBad { > private String[] myArray = ...; > > public String[] getArray() { > if( myArray == null ) { > return null; > } else { > return (String[]) myArray.clone(); > } > } > >> >> But List still lets the user modify the field which in turn modify the >> underlying array. We have gained nothing. > >The problem isn't that you're returning something the client can >modify. The problem is that you're giving the client backdoor access >into this object's private state: if you just return your internal >array any changes the client does to that array is a change in the >state of /this/. If you return a _copy_ of the internal array, or a >list created from the internal array, any changes made to the return >value by the client only affects the _client's_ state, not /this/'s. I will add your idea to http://mindprod.com/arraylist.html#ARRAYASLIST -- Roedy Green Canadian Mind Products http://mindprod.com Culture is your operating system. ~ Terence McKenna (born: 1946-11-16 died: 2000-04-03 at age: 53)