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