String[] , Arrays.asList , Collections.unmodifiableList

R

Roedy Green

I wrote a method of the form

String[] someMethod( ... )

IntelliJ complained this was a wicked thing todo.

Why? Because the caller could modify the String array it at would
wreck by copy inside SomeMethod.

So what do people do? They use Arrays.asList to convert to a List, an
java.util.Arrays$ArrayList.

But List still lets the user modify the field which in turn modify the
underlying array. We have gained nothing.

We have to use Collections.unmodifiableList which gives us a
Collections.unmodifiableList wrapper around our List that throws
UnsupportedOperationException when we attempt to write.

The catch is the set methods are still there. We don't find out about
the problem of modifying this list until run time.
 
R

Roedy Green

Roedy Green said:
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
 
S

Stanimir Stamenkov

Thu, 08 May 2014 21:30:08 -0700, /Roedy Green/:
We have to use Collections.unmodifiableList which gives us a
Collections.unmodifiableList wrapper around our List that throws
UnsupportedOperationException when we attempt to write.

The catch is the set methods are still there. We don't find out about
the problem of modifying this list until run time.

I think this more or less a general rule: Don't assume a returned
Collection (or Map) is mutable unless explicitly stated by the
documentation / contract.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top