ImmutableCollection Extension

I would like to create a data model that passes an iterator and size, basically a read-only way to iterate through the elements of a result set.

I suggested that the ImmutableCollection extension and the implementation of size () and iterator () were the best way, since this type adequately conveys my intentions.

Unfortunately, ImmutableCollection has a package-private isPartialView.

My question is: why isPartialView is a closed package, if it remains so, and if so, then what is the best way to simulate my read-only collection? Should I only create a custom type with the size () and iterator () (SizedIterable) methods? Are there any other suggestions for this use case?

+4
source share
2 answers

Many operations in the Collection interface are considered optional. You can write your own implementation and throw an UnsupportedOperationException for any actions that your implementation does not support. This will be a way around the need for an ImmutableCollection extension.

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

Continuous collection. Does not allow null elements.

Note. Although this class is not final, it cannot be subclassed outside of this package, since it does not have public or protected constructors. Thus, instances of this type guarantee immutability.

+3
source

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.

+4
source

Source: https://habr.com/ru/post/1497497/


All Articles