001    /*
002     * Copyright (C) 2007 The Guava Authors
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package com.google.common.collect;
018    
019    import static com.google.common.base.Preconditions.checkNotNull;
020    
021    import com.google.common.annotations.GwtCompatible;
022    import com.google.common.annotations.GwtIncompatible;
023    
024    import java.io.IOException;
025    import java.io.ObjectInputStream;
026    import java.io.ObjectOutputStream;
027    import java.util.Collection;
028    import java.util.Comparator;
029    import java.util.SortedMap;
030    import java.util.SortedSet;
031    import java.util.TreeMap;
032    import java.util.TreeSet;
033    
034    /**
035     * Implementation of {@code Multimap} whose keys and values are ordered by
036     * their natural ordering or by supplied comparators. In all cases, this
037     * implementation uses {@link Comparable#compareTo} or {@link
038     * Comparator#compare} instead of {@link Object#equals} to determine
039     * equivalence of instances.
040     *
041     * <p><b>Warning:</b> The comparators or comparables used must be <i>consistent
042     * with equals</i> as explained by the {@link Comparable} class specification.
043     * Otherwise, the resulting multiset will violate the general contract of {@link
044     * SetMultimap}, which it is specified in terms of {@link Object#equals}.
045     *
046     * <p>The collections returned by {@code keySet} and {@code asMap} iterate
047     * through the keys according to the key comparator ordering or the natural
048     * ordering of the keys. Similarly, {@code get}, {@code removeAll}, and {@code
049     * replaceValues} return collections that iterate through the values according
050     * to the value comparator ordering or the natural ordering of the values. The
051     * collections generated by {@code entries}, {@code keys}, and {@code values}
052     * iterate across the keys according to the above key ordering, and for each
053     * key they iterate across the values according to the value ordering.
054     *
055     * <p>The multimap does not store duplicate key-value pairs. Adding a new
056     * key-value pair equal to an existing key-value pair has no effect.
057     *
058     * <p>Null keys and values are permitted (provided, of course, that the
059     * respective comparators support them). All optional multimap methods are
060     * supported, and all returned views are modifiable.
061     *
062     * <p>This class is not threadsafe when any concurrent operations update the
063     * multimap. Concurrent read operations will work correctly. To allow concurrent
064     * update operations, wrap your multimap with a call to {@link
065     * Multimaps#synchronizedSortedSetMultimap}.
066     * 
067     * <p>See the Guava User Guide article on <a href=
068     * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap">
069     * {@code Multimap}</a>.
070     *
071     * @author Jared Levy
072     * @since 2.0 (imported from Google Collections Library)
073     */
074    @GwtCompatible(serializable = true, emulated = true)
075    public class TreeMultimap<K, V> extends AbstractSortedSetMultimap<K, V> {
076      private transient Comparator<? super K> keyComparator;
077      private transient Comparator<? super V> valueComparator;
078    
079      /**
080       * Creates an empty {@code TreeMultimap} ordered by the natural ordering of
081       * its keys and values.
082       */
083      public static <K extends Comparable, V extends Comparable>
084          TreeMultimap<K, V> create() {
085        return new TreeMultimap<K, V>(Ordering.natural(), Ordering.natural());
086      }
087    
088      /**
089       * Creates an empty {@code TreeMultimap} instance using explicit comparators.
090       * Neither comparator may be null; use {@link Ordering#natural()} to specify
091       * natural order.
092       *
093       * @param keyComparator the comparator that determines the key ordering
094       * @param valueComparator the comparator that determines the value ordering
095       */
096      public static <K, V> TreeMultimap<K, V> create(
097          Comparator<? super K> keyComparator,
098          Comparator<? super V> valueComparator) {
099        return new TreeMultimap<K, V>(checkNotNull(keyComparator),
100            checkNotNull(valueComparator));
101      }
102    
103      /**
104       * Constructs a {@code TreeMultimap}, ordered by the natural ordering of its
105       * keys and values, with the same mappings as the specified multimap.
106       *
107       * @param multimap the multimap whose contents are copied to this multimap
108       */
109      public static <K extends Comparable, V extends Comparable>
110          TreeMultimap<K, V> create(Multimap<? extends K, ? extends V> multimap) {
111        return new TreeMultimap<K, V>(Ordering.natural(), Ordering.natural(),
112            multimap);
113      }
114    
115      TreeMultimap(Comparator<? super K> keyComparator,
116          Comparator<? super V> valueComparator) {
117        super(new TreeMap<K, Collection<V>>(keyComparator));
118        this.keyComparator = keyComparator;
119        this.valueComparator = valueComparator;
120      }
121    
122      private TreeMultimap(Comparator<? super K> keyComparator,
123          Comparator<? super V> valueComparator,
124          Multimap<? extends K, ? extends V> multimap) {
125        this(keyComparator, valueComparator);
126        putAll(multimap);
127      }
128    
129      /**
130       * {@inheritDoc}
131       *
132       * <p>Creates an empty {@code TreeSet} for a collection of values for one key.
133       *
134       * @return a new {@code TreeSet} containing a collection of values for one
135       *     key
136       */
137      @Override SortedSet<V> createCollection() {
138        return new TreeSet<V>(valueComparator);
139      }
140    
141      /**
142       * Returns the comparator that orders the multimap keys.
143       */
144      public Comparator<? super K> keyComparator() {
145        return keyComparator;
146      }
147    
148      @Override
149      public Comparator<? super V> valueComparator() {
150        return valueComparator;
151      }
152    
153      /**
154       * {@inheritDoc}
155       *
156       * <p>Because a {@code TreeMultimap} has unique sorted keys, this method
157       * returns a {@link SortedSet}, instead of the {@link java.util.Set} specified
158       * in the {@link Multimap} interface.
159       */
160      @Override public SortedSet<K> keySet() {
161        return (SortedSet<K>) super.keySet();
162      }
163    
164      /**
165       * {@inheritDoc}
166       *
167       * <p>Because a {@code TreeMultimap} has unique sorted keys, this method
168       * returns a {@link SortedMap}, instead of the {@link java.util.Map} specified
169       * in the {@link Multimap} interface.
170       */
171      @Override public SortedMap<K, Collection<V>> asMap() {
172        return (SortedMap<K, Collection<V>>) super.asMap();
173      }
174    
175      /**
176       * @serialData key comparator, value comparator, number of distinct keys, and
177       *     then for each distinct key: the key, number of values for that key, and
178       *     key values
179       */
180      @GwtIncompatible("java.io.ObjectOutputStream")
181      private void writeObject(ObjectOutputStream stream) throws IOException {
182        stream.defaultWriteObject();
183        stream.writeObject(keyComparator());
184        stream.writeObject(valueComparator());
185        Serialization.writeMultimap(this, stream);
186      }
187    
188      @GwtIncompatible("java.io.ObjectInputStream")
189      @SuppressWarnings("unchecked") // reading data stored by writeObject
190      private void readObject(ObjectInputStream stream)
191          throws IOException, ClassNotFoundException {
192        stream.defaultReadObject();
193        keyComparator = checkNotNull((Comparator<? super K>) stream.readObject());
194        valueComparator = checkNotNull((Comparator<? super V>) stream.readObject());
195        setMap(new TreeMap<K, Collection<V>>(keyComparator));
196        Serialization.populateMultimap(this, stream);
197      }
198    
199      @GwtIncompatible("not needed in emulated source")
200      private static final long serialVersionUID = 0;
201    }