Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending ImmutableCollection

Tags:

java

guava

I'd like to build a data model that conveys an iterator and a size, basically a read-only way of iterating a result set's elements.

I figured extending ImmutableCollection and implementing size() and iterator() was the best course of action, since this type adequately communicates my intent.

Unfortunately, ImmutableCollection has a package-private isPartialView.

My question: Why is isPartialView package-private, should it remain so, and if so, what is the best way to model my read-only collection? Should I be creating a custom type with only the size() and iterator() methods (a SizedIterable)? Are there other suggestions for this use case?

like image 795
lhunath Avatar asked Mar 22 '23 18:03

lhunath


2 Answers

If it is not for performance issues, I would suggest you not try to create another Collection implementation. Read-only view of the collection is already provided by Java with the Collections.unmodifiableCollection() method. If you want to stay with Guava, the ImmutableList, ImmutableSet and ImmutableMap are the classes you want to check out. To determine the size, you can use the Iterables.size() method from Guava.

If performance issues are present, then implementing the scheme with a ForwardingCollection and UnmodifiableIterator can be favorable. 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());
    }
}

Caching the size is also possible with the assumption that addAll and removeAll are not used or they are funneled through the add and remove calls where house keeping can be implemented based on the return value of the delegate method. But with other restrictions, e.g. if used only for lists, the addAll can be optimized.

like image 66
allprog Avatar answered Apr 02 '23 17:04

allprog


Many of the operations in the Collection interface are considered optional. You could write your own implementation on that and throw the UnsupportedOperationException for any action your implementation does not support. This would be a way to get around having to extend ImmutableCollection.

Subclassing ImmutableCollection is probably not an option, as its documentation states the following:

An immutable collection. Does not permit null elements.

Note: Although this class is not final, it cannot be subclassed outside of this package as it has no public or protected constructors. Thus, instances of this type are guaranteed to be immutable.

like image 22
Surveon Avatar answered Apr 02 '23 15:04

Surveon