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 *      http://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;
026
027/**
028 * Decorates another {@link Bag} to comply with the Collection contract.
029 * <p>
030 * By decorating an existing {@link Bag} instance with a {@link CollectionBag},
031 * it can be safely passed on to methods that require Collection types that
032 * are fully compliant with the Collection contract.
033 * <p>
034 * The method javadoc highlights the differences compared to the original Bag interface.
035 *
036 * @see Bag
037 * @param <E> the type held in the bag
038 * @since 4.0
039 * @version $Id: CollectionBag.html 972397 2015-11-14 15:01:49Z tn $
040 */
041public final class CollectionBag<E> extends AbstractBagDecorator<E> {
042
043    /** Serialization version */
044    private static final long serialVersionUID = -2560033712679053143L;
045
046    /**
047     * Factory method to create a bag that complies to the Collection contract.
048     *
049     * @param <E> the type of the elements in the bag
050     * @param bag  the bag to decorate, must not be null
051     * @return a Bag that complies to the Collection contract
052     * @throws NullPointerException if bag is null
053     */
054    public static <E> Bag<E> collectionBag(final Bag<E> bag) {
055        return new CollectionBag<E>(bag);
056    }
057
058    //-----------------------------------------------------------------------
059    /**
060     * Constructor that wraps (not copies).
061     *
062     * @param bag  the bag to decorate, must not be null
063     * @throws NullPointerException if bag is null
064     */
065    public CollectionBag(final Bag<E> bag) {
066        super(bag);
067    }
068
069    //-----------------------------------------------------------------------
070    /**
071     * Write the collection out using a custom routine.
072     *
073     * @param out  the output stream
074     * @throws IOException
075     */
076    private void writeObject(final ObjectOutputStream out) throws IOException {
077        out.defaultWriteObject();
078        out.writeObject(decorated());
079    }
080
081    /**
082     * Read the collection in using a custom routine.
083     *
084     * @param in  the input stream
085     * @throws IOException
086     * @throws ClassNotFoundException
087     * @throws ClassCastException if deserialised object has wrong type
088     */
089    @SuppressWarnings("unchecked") // will throw CCE, see Javadoc
090    private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
091        in.defaultReadObject();
092        setCollection((Collection<E>) in.readObject());
093    }
094
095    //-----------------------------------------------------------------------
096    // Collection interface
097    //-----------------------------------------------------------------------
098
099    /**
100     * <i>(Change)</i>
101     * Returns <code>true</code> if the bag contains all elements in
102     * the given collection, <b>not</b> respecting cardinality. That is,
103     * if the given collection <code>coll</code> contains at least one of
104     * every object contained in this object.
105     *
106     * @param coll  the collection to check against
107     * @return <code>true</code> if the Bag contains at least one of every object in the collection
108     */
109    @Override
110    public boolean containsAll(final Collection<?> coll) {
111        final Iterator<?> e = coll.iterator();
112        while (e.hasNext()) {
113            if(!contains(e.next())) {
114                return false;
115            }
116        }
117        return true;
118    }
119
120    /**
121     * <i>(Change)</i>
122     * Adds one copy of the specified object to the Bag.
123     * <p>
124     * Since this method always increases the size of the bag, it
125     * will always return <code>true</code>.
126     *
127     * @param object  the object to add
128     * @return <code>true</code>, always
129     */
130    @Override
131    public boolean add(final E object) {
132        return add(object, 1);
133    }
134
135    @Override
136    public boolean addAll(final Collection<? extends E> coll) {
137        boolean changed = false;
138        final Iterator<? extends E> i = coll.iterator();
139        while (i.hasNext()) {
140            final boolean added = add(i.next(), 1);
141            changed = changed || added;
142        }
143        return changed;
144    }
145
146    /**
147     * <i>(Change)</i>
148     * Removes the first occurrence of the given object from the bag.
149     * <p>
150     * This will also remove the object from the {@link #uniqueSet()} if the
151     * bag contains no occurrence anymore of the object after this operation.
152     *
153     * @param object  the object to remove
154     * @return <code>true</code> if this call changed the collection
155     */
156    @Override
157    public boolean remove(final Object object) {
158        return remove(object, 1);
159    }
160
161    /**
162     * <i>(Change)</i>
163     * Remove all elements represented in the given collection,
164     * <b>not</b> respecting cardinality. That is, remove <i>all</i>
165     * occurrences of every object contained in the given collection.
166     *
167     * @param coll  the collection to remove
168     * @return <code>true</code> if this call changed the collection
169     */
170    @Override
171    public boolean removeAll(final Collection<?> coll) {
172        if (coll != null) {
173            boolean result = false;
174            final Iterator<?> i = coll.iterator();
175            while (i.hasNext()) {
176                final Object obj = i.next();
177                final boolean changed = remove(obj, getCount(obj));
178                result = result || changed;
179            }
180            return result;
181        } else {
182            // let the decorated bag handle the case of null argument
183            return decorated().removeAll(null);
184        }
185    }
186
187    /**
188     * <i>(Change)</i>
189     * Remove any members of the bag that are not in the given collection,
190     * <i>not</i> respecting cardinality. That is, any object in the given
191     * collection <code>coll</code> will be retained in the bag with the same
192     * number of copies prior to this operation. All other objects will be
193     * completely removed from this bag.
194     * <p>
195     * This implementation iterates over the elements of this bag, checking
196     * each element in turn to see if it's contained in <code>coll</code>.
197     * If it's not contained, it's removed from this bag. As a consequence,
198     * it is advised to use a collection type for <code>coll</code> that provides
199     * a fast (e.g. O(1)) implementation of {@link Collection#contains(Object)}.
200     *
201     * @param coll  the collection to retain
202     * @return <code>true</code> if this call changed the collection
203     */
204    @Override
205    public boolean retainAll(final Collection<?> coll) {
206        if (coll != null) {
207            boolean modified = false;
208            final Iterator<E> e = iterator();
209            while (e.hasNext()) {
210                if (!coll.contains(e.next())) {
211                    e.remove();
212                    modified = true;
213                }
214            }
215            return modified;
216        } else {
217            // let the decorated bag handle the case of null argument
218            return decorated().retainAll(null);
219        }
220    }
221
222    //-----------------------------------------------------------------------
223    // Bag interface
224    //-----------------------------------------------------------------------
225
226    /**
227     * <i>(Change)</i>
228     * Adds <code>count</code> copies of the specified object to the Bag.
229     * <p>
230     * Since this method always increases the size of the bag, it
231     * will always return <code>true</code>.
232     *
233     * @param object  the object to add
234     * @param count  the number of copies to add
235     * @return <code>true</code>, always
236     */
237    @Override
238    public boolean add(final E object, final int count) {
239        decorated().add(object, count);
240        return true;
241    }
242
243}