Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #28416

Re: String[] , Arrays.asList , Collections.unmodifiableList

From leif.roar@invalid.com (Leif Roar Moldskred)
Subject Re: String[] , Arrays.asList , Collections.unmodifiableList
Newsgroups comp.lang.java.programmer
References <bslom95b4j4s6eh4m5lfj6d3mq49uitlb3@4ax.com>
Message-ID <yemdncGlQ7bm8vHOnZ2dnUVZ8vSdnZ2d@giganews.com> (permalink)
Date 2014-05-09 01:02 -0500

Show all headers | View raw


Roedy Green <see_website@mindprod.com.invalid> 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.

-- 
Leif Roar Moldskred

Back to comp.lang.java.programmer | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

String[] , Arrays.asList , Collections.unmodifiableList Roedy Green <see_website@mindprod.com.invalid> - 2014-05-08 21:30 -0700
  Re: String[] , Arrays.asList , Collections.unmodifiableList leif.roar@invalid.com (Leif Roar Moldskred) - 2014-05-09 01:02 -0500
    Re: String[] , Arrays.asList , Collections.unmodifiableList Roedy Green <see_website@mindprod.com.invalid> - 2014-05-09 09:25 -0700
      Re: String[] , Arrays.asList , Collections.unmodifiableList leif.roar@invalid.com (Leif Roar Moldskred) - 2014-05-09 12:45 -0500
  Re: String[] , Arrays.asList , Collections.unmodifiableList Stanimir Stamenkov <s7an10@netscape.net> - 2014-05-11 00:09 +0300

csiph-web