ImmutableList.copyOf() creates an immutable copy of it's arguments as a List. Wherever your code stores a List parameter, it may need an immutable copy. With the JDK, coping and preventing modification requires two steps. Lists.immutableList simplifies this code:
Before:
public Directions(Address from, Address to, List<Step> steps) {
this.from = from;
this.to = to;
this.steps = Collections.unmodifiableList(new ArrayList<Step>(steps));
}After:
public Directions(Address from, Address to, List<Step> steps) {
this.from = from;
this.to = to;
this.steps = ImmutableList.of(steps);
}As usual with Google Collections, all the expected overloadings are available. There's versions that accept Iterable, Iterator, and varargs/arrays. As a special treat, there's even an overloading that takes zero parameters which allows you to add and remove elements freely without changing the signature.
Part 6

2 comments:
Sorry to be a grammar cop, but this series is valuable so I want to make it better. "It's" only means the contraction of "it is," never the possessive, which has no apostrophe: "its."
API change
ImmutableList imlist = ImmutableList.copyOf(Iterables.filter(list, high));
had to remove the type since glogger though it was html...
Post a Comment