All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.jhotdraw8.icollection.facade.ReadOnlyCollectionFacade Maven / Gradle / Ivy

/*
 * @(#)ReadOnlyCollectionFacade.java
 * Copyright © 2023 The authors and contributors of JHotDraw. MIT License.
 */
package org.jhotdraw8.icollection.facade;

import org.jhotdraw8.icollection.impl.iteration.IteratorSpliterator;
import org.jhotdraw8.icollection.readonly.AbstractReadOnlyCollection;
import org.jhotdraw8.icollection.readonly.ReadOnlyCollection;
import org.jhotdraw8.icollection.readonly.ReadOnlySet;
import org.jspecify.annotations.Nullable;

import java.util.Collection;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.IntSupplier;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * Provides a {@link ReadOnlyCollection} facade to a set of {@code Collection} functions.
 *
 * @param  the element type
 * @author Werner Randelshofer
 */
public class ReadOnlyCollectionFacade extends AbstractReadOnlyCollection {

    protected final Supplier> iteratorFunction;
    protected final IntSupplier sizeFunction;
    protected final Predicate containsFunction;
    protected final int characteristics;


    public ReadOnlyCollectionFacade(Supplier> iteratorFunction,
                                    @Nullable IntSupplier sizeFunction,
                                    Predicate containsFunction, int characteristics) {
        this.iteratorFunction = iteratorFunction;
        this.sizeFunction = sizeFunction;
        this.containsFunction = containsFunction;
        this.characteristics = characteristics;
    }

    public ReadOnlyCollectionFacade(Collection c) {
        this(c::iterator, c::size, c::contains, Spliterator.SIZED | Spliterator.SUBSIZED);
    }

    @Override
    public int size() {
        return sizeFunction.getAsInt();
    }

    @Override
    public boolean contains(Object o) {
        return containsFunction.test(o);
    }

    @Override
    public Iterator iterator() {
        return new Iterator<>() {
            private final Iterator i = iteratorFunction.get();

            @Override
            public boolean hasNext() {
                return i.hasNext();
            }

            @Override
            public E next() {
                return i.next();
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
    }

    @Override
    public Spliterator spliterator() {
        return new IteratorSpliterator<>(iterator(), size(), characteristics, null);
    }

    @Override
    public boolean equals(Object o) {
        return ReadOnlySet.setEquals(new ReadOnlySetFacade<>(this), o);
    }

    @Override
    public int hashCode() {
        return ReadOnlySet.iteratorToHashCode(iteratorFunction.get());
    }
}