Hi,

On 3/26/19 7:44 PM, Daniel Fuchs wrote:
Hi Peter,

On 26/03/2019 18:01, Peter Levart wrote:
Would such method addition be worth it?

Here is the impl of Set.copyOf:

    static <E> Set<E> copyOf(Collection<? extends E> coll) {
        if (coll instanceof ImmutableCollections.AbstractImmutableSet) {
            return (Set<E>)coll;
        } else {
            return (Set<E>)Set.of(new HashSet<>(coll).toArray());
        }
    }


Yes, and that method is suitable for situations where there is a chance of one or the other case and the user is aware of performance implications of either case. There are other situations where the code guarantees that the Set at hand is already immutable and programmer might just want to verify that as a post-condition before returning it. In that case the non-immutability would be considered an error. I'm thinking of the following implementation:

    static <E> Set<E> requireImmutable(Set<E> set) {
        if (set instanceof ImmutableCollections.AbstractImmutableSet) {
            return set;
        } else {
            throw new IllegalStateException("Not an immutable Set");
        }
    }

Currently the immutable implementation classes are package-private so there's no way for 3rd party code (short of introspecting the class hierarchy of the implementation class against the FQN of the AbstractImmutableSet class, which might be costly and fragile) to implement a helper method like this.

Regards, Peter

Best regards,

-- daniel

Reply via email to