I am looking for sample code which explains Guava ForwardingList class. Basically I am implementing a custom ArrayList class which will be used to solve this requirement mentioned in my earlier SO question. I never used Google collection before. But by just looking at the JavaDoc of ForwardingList, I think I can implement my custom class by sub classing ForwardingList.
I am looking for sample code which explains Guava ForwardingList class. Basically I am
Share
ForwardingList(whichextends ForwardingCollection, which in turnextends ForwardingObject) implements the decorator pattern.To use, you simply need to do two things:
@Override delegate()to return the backing delegate instance that methods are forwarded to@OverridewhateverListmethod you want/need to decorateThe decorator pattern allows you to use composition instead of inheritance (Effective Java 2nd Edition, Favor composition over inheritance), and
ForwardingListfrom Guava provides a convenient template from which to write your ownListimplementation, providing all the plumbing mechanism for you.Note that if you are planning to decorate an
ArrayList, you’d probably want yourForwardingListsubclass to also implementRandomAccess.Example:
ListWithDefaultHere’s an (incomplete!) example of a
ForwardingListthat substitutesnullvalues in the delegate with a given default value.We can then test it as follows:
Note that this is an incomplete implementation. The
toString()method still returns the delegate’stoString(), which isn’t aware of the default value. A few other methods must be@Overrideas well for a more complete implementation.