    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.io.Serializable;
    023import java.util.Collection;
    024import java.util.Comparator;
    025import java.util.Objects;
    026import java.util.SortedMap;
    027import java.util.TreeMap;
    028
    029import org.apache.commons.collections4.SortedBag;
    030
    031/**
    032 * Implements {@link SortedBag}, using a {@link TreeMap} to provide the data storage.
    033 * This is the standard implementation of a sorted bag.
    034 * <p>
    035 * Order will be maintained among the bag members and can be viewed through the iterator.
    036 * </p>
    037 * <p>
    038 * A {@link org.apache.commons.collections4.Bag Bag} stores each object in the collection
    039 * together with a count of occurrences. Extra methods on the interface allow multiple
    040 * copies of an object to be added or removed at once. It is important to read the interface
    041 * Javadoc carefully as several methods violate the {@link Collection} interface specification.
    042 * </p>
    043 *
    044 * @param <E> the type of elements in this bag
    045 * @since 3.0 (previously in main package v2.0)
    046 */
    047public class TreeBag<E> extends AbstractMapBag<E> implements SortedBag<E>, Serializable {
    048
    049    /** Serial version lock */
    050    private static final long serialVersionUID = -7740146511091606676L;
    051
    052    /**
    053     * Constructs an empty {@link TreeBag}.
    054     */
    055    public TreeBag() {
    056        super(new TreeMap<>());
    057    }
    058
    059    /**
    060     * Constructs a {@link TreeBag} containing all the members of the
    061     * specified collection.
    062     *
    063     * @param coll the collection to copy into the bag
    064     */
    065    public TreeBag(final Collection<? extends E> coll) {
    066        this();
    067        addAll(coll);
    068    }
    069
    070    /**
    071     * Constructs an empty bag that maintains order on its unique representative
    072     * members according to the given {@link Comparator}.
    073     *
    074     * @param comparator the comparator to use
    075     */
    076    public TreeBag(final Comparator<? super E> comparator) {
    077        super(new TreeMap<>(comparator));
    078    }
    079
    080    /**
    081     * Constructs a bag containing all the members of the given Iterable.
    082     *
    083     * @param iterable an iterable to copy into this bag.
    084     * @since 4.5.0-M3
    085     */
    086    public TreeBag(final Iterable<? extends E> iterable) {
    087        super(new TreeMap<>(), iterable);
    088    }
    089
    090    /**
    091     * {@inheritDoc}
    092     *
    093     * @throws IllegalArgumentException if the object to be added does not implement
    094     * {@link Comparable} and the {@link TreeBag} is using natural ordering
    095     * @throws NullPointerException if the specified key is null and this bag uses
    096     * natural ordering, or its comparator does not permit null keys
    097     */
    098    @Override
    099    public boolean add(final E object) {
    100        if (comparator() == null && !(object instanceof Comparable)) {
    101            Objects.requireNonNull(object, "object");
    102            throw new IllegalArgumentException("Objects of type " + object.getClass() + " cannot be added to " +
    103                                               "a naturally ordered TreeBag as it does not implement Comparable");
    104        }
    105        return super.add(object);
    106    }
    107
    108    @Override
    109    public Comparator<? super E> comparator() {
    110        return getMap().comparator();
    111    }
    112
    113    @Override
    114    public E first() {
    115        return getMap().firstKey();
    116    }
    117
    118    @Override
    119    protected SortedMap<E, AbstractMapBag.MutableInteger> getMap() {
    120        return (SortedMap<E, AbstractMapBag.MutableInteger>) super.getMap();
    121    }
    122
    123    @Override
    124    public E last() {
    125        return getMap().lastKey();
    126    }
    127
    128    /**
    129     * Deserializes the bag in using a custom routine.
    130     *
    131     * @param in  the input stream
    132     * @throws IOException if an error occurs while reading from the stream
    133     * @throws ClassNotFoundException if an object read from the stream cannot be loaded
    134     */
    135    private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
    136        in.defaultReadObject();
    137        @SuppressWarnings("unchecked")  // This will fail at runtime if the stream is incorrect
    138        final Comparator<? super E> comp = (Comparator<? super E>) in.readObject();
    139        super.doReadObject(new TreeMap<>(comp), in);
    140    }
    141
    142    /**
    143     * Serializes this object to an ObjectOutputStream.
    144     *
    145     * @param out the target ObjectOutputStream.
    146     * @throws IOException thrown when an I/O errors occur writing to the target stream.
    147     */
    148    private void writeObject(final ObjectOutputStream out) throws IOException {
    149        out.defaultWriteObject();
    150        out.writeObject(comparator());
    151        super.doWriteObject(out);
    152    }
    153
    154}