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