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
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkNotNull;
020
021import com.google.common.annotations.GwtCompatible;
022import com.google.common.annotations.GwtIncompatible;
023import java.io.IOException;
024import java.io.ObjectInputStream;
025import java.io.ObjectOutputStream;
026import java.util.Collection;
027import java.util.Comparator;
028import java.util.NavigableMap;
029import java.util.NavigableSet;
030import java.util.SortedSet;
031import java.util.TreeMap;
032import java.util.TreeSet;
033import javax.annotation.Nullable;
034
035/**
036 * Implementation of {@code Multimap} whose keys and values are ordered by
037 * their natural ordering or by supplied comparators. In all cases, this
038 * implementation uses {@link Comparable#compareTo} or {@link
039 * Comparator#compare} instead of {@link Object#equals} to determine
040 * equivalence of instances.
041 *
042 * <p><b>Warning:</b> The comparators or comparables used must be <i>consistent
043 * with equals</i> as explained by the {@link Comparable} class specification.
044 * Otherwise, the resulting multiset will violate the general contract of {@link
045 * SetMultimap}, which it is specified in terms of {@link Object#equals}.
046 *
047 * <p>The collections returned by {@code keySet} and {@code asMap} iterate
048 * through the keys according to the key comparator ordering or the natural
049 * ordering of the keys. Similarly, {@code get}, {@code removeAll}, and {@code
050 * replaceValues} return collections that iterate through the values according
051 * to the value comparator ordering or the natural ordering of the values. The
052 * collections generated by {@code entries}, {@code keys}, and {@code values}
053 * iterate across the keys according to the above key ordering, and for each
054 * key they iterate across the values according to the value ordering.
055 *
056 * <p>The multimap does not store duplicate key-value pairs. Adding a new
057 * key-value pair equal to an existing key-value pair has no effect.
058 *
059 * <p>Null keys and values are permitted (provided, of course, that the
060 * respective comparators support them). All optional multimap methods are
061 * supported, and all returned views are modifiable.
062 *
063 * <p>This class is not threadsafe when any concurrent operations update the
064 * multimap. Concurrent read operations will work correctly. To allow concurrent
065 * update operations, wrap your multimap with a call to {@link
066 * Multimaps#synchronizedSortedSetMultimap}.
067 *
068 * <p>See the Guava User Guide article on <a href=
069 * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#multimap">
070 * {@code Multimap}</a>.
071 *
072 * @author Jared Levy
073 * @author Louis Wasserman
074 * @since 2.0
075 */
076@GwtCompatible(serializable = true, emulated = true)
077public class TreeMultimap<K, V> extends AbstractSortedKeySortedSetMultimap<K, V> {
078  private transient Comparator<? super K> keyComparator;
079  private transient Comparator<? super V> valueComparator;
080
081  /**
082   * Creates an empty {@code TreeMultimap} ordered by the natural ordering of
083   * its keys and values.
084   */
085  public static <K extends Comparable, V extends Comparable> TreeMultimap<K, V> create() {
086    return new TreeMultimap<K, V>(Ordering.natural(), Ordering.natural());
087  }
088
089  /**
090   * Creates an empty {@code TreeMultimap} instance using explicit comparators.
091   * Neither comparator may be null; use {@link Ordering#natural()} to specify
092   * natural order.
093   *
094   * @param keyComparator the comparator that determines the key ordering
095   * @param valueComparator the comparator that determines the value ordering
096   */
097  public static <K, V> TreeMultimap<K, V> create(
098      Comparator<? super K> keyComparator, Comparator<? super V> valueComparator) {
099    return new TreeMultimap<K, V>(checkNotNull(keyComparator), checkNotNull(valueComparator));
100  }
101
102  /**
103   * Constructs a {@code TreeMultimap}, ordered by the natural ordering of its
104   * keys and values, with the same mappings as the specified multimap.
105   *
106   * @param multimap the multimap whose contents are copied to this multimap
107   */
108  public static <K extends Comparable, V extends Comparable> TreeMultimap<K, V> create(
109      Multimap<? extends K, ? extends V> multimap) {
110    return new TreeMultimap<K, V>(Ordering.natural(), Ordering.natural(), multimap);
111  }
112
113  TreeMultimap(Comparator<? super K> keyComparator, Comparator<? super V> valueComparator) {
114    super(new TreeMap<K, Collection<V>>(keyComparator));
115    this.keyComparator = keyComparator;
116    this.valueComparator = valueComparator;
117  }
118
119  private TreeMultimap(
120      Comparator<? super K> keyComparator,
121      Comparator<? super V> valueComparator,
122      Multimap<? extends K, ? extends V> multimap) {
123    this(keyComparator, valueComparator);
124    putAll(multimap);
125  }
126
127  /**
128   * {@inheritDoc}
129   *
130   * <p>Creates an empty {@code TreeSet} for a collection of values for one key.
131   *
132   * @return a new {@code TreeSet} containing a collection of values for one
133   *     key
134   */
135  @Override
136  SortedSet<V> createCollection() {
137    return new TreeSet<V>(valueComparator);
138  }
139
140  @Override
141  Collection<V> createCollection(@Nullable K key) {
142    if (key == null) {
143      keyComparator().compare(key, key);
144    }
145    return super.createCollection(key);
146  }
147
148  /**
149   * Returns the comparator that orders the multimap keys.
150   */
151  public Comparator<? super K> keyComparator() {
152    return keyComparator;
153  }
154
155  @Override
156  public Comparator<? super V> valueComparator() {
157    return valueComparator;
158  }
159
160  /*
161   * The following @GwtIncompatible methods override the methods in
162   * AbstractSortedKeySortedSetMultimap, so GWT will fall back to the ASKSSM implementations,
163   * which return SortedSets and SortedMaps.
164   */
165
166  @Override
167  @GwtIncompatible // NavigableMap
168  NavigableMap<K, Collection<V>> backingMap() {
169    return (NavigableMap<K, Collection<V>>) super.backingMap();
170  }
171
172  /**
173   * @since 14.0 (present with return type {@code SortedSet} since 2.0)
174   */
175  @Override
176  @GwtIncompatible // NavigableSet
177  public NavigableSet<V> get(@Nullable K key) {
178    return (NavigableSet<V>) super.get(key);
179  }
180
181  @Override
182  @GwtIncompatible // NavigableSet
183  Collection<V> unmodifiableCollectionSubclass(Collection<V> collection) {
184    return Sets.unmodifiableNavigableSet((NavigableSet<V>) collection);
185  }
186
187  @Override
188  @GwtIncompatible // NavigableSet
189  Collection<V> wrapCollection(K key, Collection<V> collection) {
190    return new WrappedNavigableSet(key, (NavigableSet<V>) collection, null);
191  }
192
193  /**
194   * {@inheritDoc}
195   *
196   * <p>Because a {@code TreeMultimap} has unique sorted keys, this method
197   * returns a {@link NavigableSet}, instead of the {@link java.util.Set} specified
198   * in the {@link Multimap} interface.
199   *
200   * @since 14.0 (present with return type {@code SortedSet} since 2.0)
201   */
202  @Override
203  @GwtIncompatible // NavigableSet
204  public NavigableSet<K> keySet() {
205    return (NavigableSet<K>) super.keySet();
206  }
207
208  @Override
209  @GwtIncompatible // NavigableSet
210  NavigableSet<K> createKeySet() {
211    return new NavigableKeySet(backingMap());
212  }
213
214  /**
215   * {@inheritDoc}
216   *
217   * <p>Because a {@code TreeMultimap} has unique sorted keys, this method
218   * returns a {@link NavigableMap}, instead of the {@link java.util.Map} specified
219   * in the {@link Multimap} interface.
220   *
221   * @since 14.0 (present with return type {@code SortedMap} since 2.0)
222   */
223  @Override
224  @GwtIncompatible // NavigableMap
225  public NavigableMap<K, Collection<V>> asMap() {
226    return (NavigableMap<K, Collection<V>>) super.asMap();
227  }
228
229  @Override
230  @GwtIncompatible // NavigableMap
231  NavigableMap<K, Collection<V>> createAsMap() {
232    return new NavigableAsMap(backingMap());
233  }
234
235  /**
236   * @serialData key comparator, value comparator, number of distinct keys, and
237   *     then for each distinct key: the key, number of values for that key, and
238   *     key values
239   */
240  @GwtIncompatible // java.io.ObjectOutputStream
241  private void writeObject(ObjectOutputStream stream) throws IOException {
242    stream.defaultWriteObject();
243    stream.writeObject(keyComparator());
244    stream.writeObject(valueComparator());
245    Serialization.writeMultimap(this, stream);
246  }
247
248  @GwtIncompatible // java.io.ObjectInputStream
249  @SuppressWarnings("unchecked") // reading data stored by writeObject
250  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
251    stream.defaultReadObject();
252    keyComparator = checkNotNull((Comparator<? super K>) stream.readObject());
253    valueComparator = checkNotNull((Comparator<? super V>) stream.readObject());
254    setMap(new TreeMap<K, Collection<V>>(keyComparator));
255    Serialization.populateMultimap(this, stream);
256  }
257
258  @GwtIncompatible // not needed in emulated source
259  private static final long serialVersionUID = 0;
260}