If this does not concern performance problems, I would suggest you not try to create another implementation of Collection. A read-only view of the collection is already provided by Java using the Collections.unmodifiableCollection() method. If you want to stay with Guava, ImmutableList , ImmutableSet and ImmutableMap are the classes you want to test. To determine the size, you can use the Iterables.size() method from Guava.
If performance problems are present, then implementing a scheme with ForwardingCollection and UnmodifiableIterator may be beneficial. Example:
public static class CollectionWithUnmodifiableIterator<E> extends ForwardingCollection<E> { private final Collection<E> collection; public CollectionWithUnmodifiableIterator(final Collection<E> collection) { this.collection = collection; } @Override protected Collection<E> delegate() { return collection; } @Override public Iterator<E> iterator() { return Iterators.unmodifiableIterator(super.iterator()); } }
Size caching is also possible with the assumption that addAll and removeAll not used or that they are routed by calls to add and remove , where house keeping can be implemented based on the delegate return value. But with other restrictions, for example. if used only for lists, addAll can be optimized.
source share