Atom Feed SITE FEED   ADD TO GOOGLE READER

Coding in the small with Google Collections: Lists.immutableList

Part 5 in a Series.

Lists.immutableList() 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 = Lists.immutableList(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