TreeBag.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.collections4.bag;

  18. import java.io.IOException;
  19. import java.io.ObjectInputStream;
  20. import java.io.ObjectOutputStream;
  21. import java.io.Serializable;
  22. import java.util.Collection;
  23. import java.util.Comparator;
  24. import java.util.Objects;
  25. import java.util.SortedMap;
  26. import java.util.TreeMap;

  27. import org.apache.commons.collections4.SortedBag;

  28. /**
  29.  * Implements {@link SortedBag}, using a {@link TreeMap} to provide the data storage.
  30.  * This is the standard implementation of a sorted bag.
  31.  * <p>
  32.  * Order will be maintained among the bag members and can be viewed through the iterator.
  33.  * </p>
  34.  * <p>
  35.  * A {@link org.apache.commons.collections4.Bag Bag} stores each object in the collection
  36.  * together with a count of occurrences. Extra methods on the interface allow multiple
  37.  * copies of an object to be added or removed at once. It is important to read the interface
  38.  * Javadoc carefully as several methods violate the {@link Collection} interface specification.
  39.  * </p>
  40.  *
  41.  * @param <E> the type of elements in this bag
  42.  * @since 3.0 (previously in main package v2.0)
  43.  */
  44. public class TreeBag<E> extends AbstractMapBag<E> implements SortedBag<E>, Serializable {

  45.     /** Serial version lock */
  46.     private static final long serialVersionUID = -7740146511091606676L;

  47.     /**
  48.      * Constructs an empty {@link TreeBag}.
  49.      */
  50.     public TreeBag() {
  51.         super(new TreeMap<>());
  52.     }

  53.     /**
  54.      * Constructs a {@link TreeBag} containing all the members of the
  55.      * specified collection.
  56.      *
  57.      * @param coll the collection to copy into the bag
  58.      */
  59.     public TreeBag(final Collection<? extends E> coll) {
  60.         this();
  61.         addAll(coll);
  62.     }

  63.     /**
  64.      * Constructs an empty bag that maintains order on its unique representative
  65.      * members according to the given {@link Comparator}.
  66.      *
  67.      * @param comparator the comparator to use
  68.      */
  69.     public TreeBag(final Comparator<? super E> comparator) {
  70.         super(new TreeMap<>(comparator));
  71.     }

  72.     /**
  73.      * Constructs a bag containing all the members of the given Iterable.
  74.      *
  75.      * @param iterable an iterable to copy into this bag.
  76.      * @since 4.5.0-M3
  77.      */
  78.     public TreeBag(final Iterable<? extends E> iterable) {
  79.         super(new TreeMap<>(), iterable);
  80.     }

  81.     /**
  82.      * {@inheritDoc}
  83.      *
  84.      * @throws IllegalArgumentException if the object to be added does not implement
  85.      * {@link Comparable} and the {@link TreeBag} is using natural ordering
  86.      * @throws NullPointerException if the specified key is null and this bag uses
  87.      * natural ordering, or its comparator does not permit null keys
  88.      */
  89.     @Override
  90.     public boolean add(final E object) {
  91.         if (comparator() == null && !(object instanceof Comparable)) {
  92.             Objects.requireNonNull(object, "object");
  93.             throw new IllegalArgumentException("Objects of type " + object.getClass() + " cannot be added to " +
  94.                                                "a naturally ordered TreeBag as it does not implement Comparable");
  95.         }
  96.         return super.add(object);
  97.     }

  98.     @Override
  99.     public Comparator<? super E> comparator() {
  100.         return getMap().comparator();
  101.     }

  102.     @Override
  103.     public E first() {
  104.         return getMap().firstKey();
  105.     }

  106.     @Override
  107.     protected SortedMap<E, AbstractMapBag.MutableInteger> getMap() {
  108.         return (SortedMap<E, AbstractMapBag.MutableInteger>) super.getMap();
  109.     }

  110.     @Override
  111.     public E last() {
  112.         return getMap().lastKey();
  113.     }

  114.     /**
  115.      * Deserializes the bag in using a custom routine.
  116.      *
  117.      * @param in  the input stream
  118.      * @throws IOException if an error occurs while reading from the stream
  119.      * @throws ClassNotFoundException if an object read from the stream cannot be loaded
  120.      */
  121.     private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
  122.         in.defaultReadObject();
  123.         @SuppressWarnings("unchecked")  // This will fail at runtime if the stream is incorrect
  124.         final Comparator<? super E> comp = (Comparator<? super E>) in.readObject();
  125.         super.doReadObject(new TreeMap<>(comp), in);
  126.     }

  127.     /**
  128.      * Serializes this object to an ObjectOutputStream.
  129.      *
  130.      * @param out the target ObjectOutputStream.
  131.      * @throws IOException thrown when an I/O errors occur writing to the target stream.
  132.      */
  133.     private void writeObject(final ObjectOutputStream out) throws IOException {
  134.         out.defaultWriteObject();
  135.         out.writeObject(comparator());
  136.         super.doWriteObject(out);
  137.     }

  138. }