    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      https://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.collections4.bag;
    018
    019import java.io.IOException;
    020import java.io.ObjectInputStream;
    021import java.io.ObjectOutputStream;
    022import java.util.Collection;
    023import java.util.Iterator;
    024
    025import org.apache.commons.collections4.Bag;
    026import org.apache.commons.collections4.MultiSet;
    027
    028/**
    029 * Decorates another {@link Bag} to comply with the Collection contract.
    030 * <p>
    031 * By decorating an existing {@link Bag} instance with a {@link CollectionBag},
    032 * it can be safely passed on to methods that require Collection types that
    033 * are fully compliant with the Collection contract.
    034 * </p>
    035 * <p>
    036 * The method Javadoc highlights the differences compared to the original Bag interface.
    037 * </p>
    038 *
    039 * @see Bag
    040 * @param <E> The type of elements in this bag
    041 * @since 4.0
    042 * @deprecated Since 4.6.0, no longer needed; a {@link MultiSet} already complies with the {@link Collection} contract.
    043 */
    044@Deprecated
    045public final class CollectionBag<E> extends AbstractBagDecorator<E> {
    046
    047    /** Serialization version */
    048    private static final long serialVersionUID = -2560033712679053143L;
    049
    050    /**
    051     * Factory method to create a bag that complies to the Collection contract.
    052     *
    053     * @param <E> The type of the elements in the bag
    054     * @param bag  The bag to decorate, must not be null
    055     * @return A Bag that complies to the Collection contract
    056     * @throws NullPointerException if bag is null
    057     */
    058    public static <E> Bag<E> collectionBag(final Bag<E> bag) {
    059        return new CollectionBag<>(bag);
    060    }
    061
    062    /**
    063     * Constructor that wraps (not copies).
    064     *
    065     * @param bag  The bag to decorate, must not be null
    066     * @throws NullPointerException if bag is null
    067     */
    068    public CollectionBag(final Bag<E> bag) {
    069        super(bag);
    070    }
    071
    072    /**
    073     * <em>(Change)</em> Adds one copy of the specified object to the Bag.
    074     * <p>
    075     * Since this method always increases the size of the bag, it will always return {@code true}.
    076     * </p>
    077     *
    078     * @param object The object to add
    079     * @return {@code true}, always
    080     * @throws ClassCastException if the class of the specified element prevents it from being added to this collection
    081     */
    082    @Override
    083    public boolean add(final E object) {
    084        return add(object, 1);
    085    }
    086
    087    /**
    088     * <em>(Change)</em>
    089     * Adds {@code count} copies of the specified object to the Bag.
    090     * <p>
    091     * Since this method always increases the size of the bag, it
    092     * will always return {@code true}.
    093     *
    094     * @param object  The object to add
    095     * @param count  The number of copies to add
    096     * @return {@code true}, always
    097     * @throws ClassCastException if the class of the specified element prevents it from being added to this collection
    098     */
    099    @Override
    100    public boolean add(final E object, final int count) {
    101        decorated().add(object, count);
    102        return true;
    103    }
    104
    105    @Override
    106    public boolean addAll(final Collection<? extends E> coll) {
    107        boolean changed = false;
    108        for (final E current : coll) {
    109            final boolean added = add(current, 1);
    110            changed = changed || added;
    111        }
    112        return changed;
    113    }
    114
    115    /**
    116     * <em>(Change)</em>
    117     * Returns {@code true} if the bag contains all elements in
    118     * the given collection, <strong>not</strong> respecting cardinality. That is,
    119     * if the given collection {@code coll} contains at least one of
    120     * every object contained in this object.
    121     *
    122     * @param coll  The collection to check against
    123     * @return {@code true} if the Bag contains at least one of every object in the collection
    124     */
    125    @Override
    126    public boolean containsAll(final Collection<?> coll) {
    127        return coll.stream().allMatch(this::contains);
    128    }
    129
    130    /**
    131     * Reads the collection in using a custom routine.
    132     *
    133     * @param in  The input stream
    134     * @throws IOException Thrown if an error occurs while reading from the stream
    135     * @throws ClassNotFoundException if an object read from the stream cannot be loaded
    136     * @throws ClassCastException if deserialized object has wrong type
    137     */
    138    @SuppressWarnings("unchecked") // will throw CCE, see Javadoc
    139    private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
    140        in.defaultReadObject();
    141        setCollection((Collection<E>) in.readObject());
    142    }
    143
    144    /**
    145     * <em>(Change)</em>
    146     * Removes the first occurrence of the given object from the bag.
    147     * <p>
    148     * This will also remove the object from the {@link #uniqueSet()} if the
    149     * bag contains no occurrence anymore of the object after this operation.
    150     * </p>
    151     *
    152     * @param object  The object to remove
    153     * @return {@code true} if this call changed the collection
    154     */
    155    @Override
    156    public boolean remove(final Object object) {
    157        return remove(object, 1);
    158    }
    159
    160    /**
    161     * <em>(Change)</em>
    162     * Remove all elements represented in the given collection,
    163     * <strong>not</strong> respecting cardinality. That is, remove <em>all</em>
    164     * occurrences of every object contained in the given collection.
    165     *
    166     * @param coll  The collection to remove
    167     * @return {@code true} if this call changed the collection
    168     */
    169    @Override
    170    public boolean removeAll(final Collection<?> coll) {
    171        if (coll != null) {
    172            boolean result = false;
    173            for (final Object obj : coll) {
    174                final boolean changed = remove(obj, getCount(obj));
    175                result = result || changed;
    176            }
    177            return result;
    178        }
    179        // let the decorated bag handle the case of null argument
    180        return decorated().removeAll(null);
    181    }
    182
    183    /**
    184     * <em>(Change)</em>
    185     * Remove any members of the bag that are not in the given collection,
    186     * <em>not</em> respecting cardinality. That is, any object in the given
    187     * collection {@code coll} will be retained in the bag with the same
    188     * number of copies prior to this operation. All other objects will be
    189     * completely removed from this bag.
    190     * <p>
    191     * This implementation iterates over the elements of this bag, checking
    192     * each element in turn to see if it's contained in {@code coll}.
    193     * If it's not contained, it's removed from this bag. As a consequence,
    194     * it is advised to use a collection type for {@code coll} that provides
    195     * a fast (for example O(1)) implementation of {@link Collection#contains(Object)}.
    196     * </p>
    197     *
    198     * @param coll  The collection to retain
    199     * @return {@code true} if this call changed the collection
    200     */
    201    @Override
    202    public boolean retainAll(final Collection<?> coll) {
    203        if (coll != null) {
    204            boolean modified = false;
    205            final Iterator<E> e = iterator();
    206            while (e.hasNext()) {
    207                if (!coll.contains(e.next())) {
    208                    e.remove();
    209                    modified = true;
    210                }
    211            }
    212            return modified;
    213        }
    214        // let the decorated bag handle the case of null argument
    215        return decorated().retainAll(null);
    216    }
    217
    218    /**
    219     * Writes the collection out using a custom routine.
    220     *
    221     * @param out  The output stream
    222     * @throws IOException Thrown if an error occurs while writing to the stream
    223     */
    224    private void writeObject(final ObjectOutputStream out) throws IOException {
    225        out.defaultWriteObject();
    226        out.writeObject(decorated());
    227    }
    228
    229}