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