Atom Feed SITE FEED   ADD TO GOOGLE READER

Coding in the small with Google Collections: ImmutableList.copyOf

Part 5 in a Series.

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
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...