Java Reference
In-Depth Information
Now let's look at defining insertAll. Here's the first danger point. Suppose you defined insertAll
so that it mutated its arguments, perhaps by updating all the elements of subans to contain first.
Then the program would incorrectly cause subans to be modified in the same way as subans2,
resulting in an answer mysteriously containing eight copies of {1,4,9}. You instead define
insertAll functionally as follows:
Note that you're creating a new List that contains all the elements of subans. You take advantage
of the fact that an Integer object is immutable (otherwise you'd have to clone each element too).
The focus caused by thinking of methods like insertAll as functional gives you a natural place to
put all this careful copying code—inside insertAll rather in its callers.
Finally, you need to define the method concat. In this case, there's a simple solution, which we
beg you not to use (we show it only so you can compare the different styles):
static List<List<Integer>> concat(List<List<Integer>> a,
List<List<Integer>> b) {
a.addAll(b);
return a;
}
Instead, we suggest you write this:
static List<List<Integer>> concat(List<List<Integer>> a,
List<List<Integer>> b) {
List<List<Integer>> r = new ArrayList<>(a);
r.addAll(b);
return r;
}
Why? The second version of concat is a pure function. It may be using mutation (adding
elements to the list r) internally, but it returns a result based on its arguments and modifies
 
Search WWH ::




Custom Search