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.Set;
030import java.util.SortedMap;
031import java.util.SortedSet;
032import java.util.TreeMap;
033import java.util.TreeSet;
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>Depending on the comparators, null keys and values may or may not be
060 * supported. The natural ordering does not support nulls. All optional multimap
061 * methods are 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 * @author Jared Levy
069 * @since 2 (imported from Google Collections Library)
070 */
071@GwtCompatible(serializable = true, emulated = true)
072public class TreeMultimap<K, V> extends AbstractSortedSetMultimap<K, V> {
073  private transient Comparator<? super K> keyComparator;
074  private transient Comparator<? super V> valueComparator;
075
076  /**
077   * Creates an empty {@code TreeMultimap} ordered by the natural ordering of
078   * its keys and values.
079   */
080  @SuppressWarnings("unchecked") // eclipse doesn't like the raw Comparable
081  public static <K extends Comparable, V extends Comparable>
082      TreeMultimap<K, V> create() {
083    return new TreeMultimap<K, V>(Ordering.natural(), Ordering.natural());
084  }
085
086  /**
087   * Creates an empty {@code TreeMultimap} instance using explicit comparators.
088   * Neither comparator may be null; use {@link Ordering#natural()} to specify
089   * natural order.
090   *
091   * @param keyComparator the comparator that determines the key ordering
092   * @param valueComparator the comparator that determines the value ordering
093   */
094  public static <K, V> TreeMultimap<K, V> create(
095      Comparator<? super K> keyComparator,
096      Comparator<? super V> valueComparator) {
097    return new TreeMultimap<K, V>(checkNotNull(keyComparator),
098        checkNotNull(valueComparator));
099  }
100
101  /**
102   * Constructs a {@code TreeMultimap}, ordered by the natural ordering of its
103   * keys and values, with the same mappings as the specified multimap.
104   *
105   * @param multimap the multimap whose contents are copied to this multimap
106   */
107  @SuppressWarnings("unchecked") // eclipse doesn't like the raw Comparable
108  public static <K extends Comparable, V extends Comparable>
109      TreeMultimap<K, V> create(Multimap<? extends K, ? extends V> multimap) {
110    return new TreeMultimap<K, V>(Ordering.natural(), Ordering.natural(),
111        multimap);
112  }
113
114  TreeMultimap(Comparator<? super K> keyComparator,
115      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(Comparator<? super K> keyComparator,
122      Comparator<? super V> valueComparator,
123      Multimap<? extends K, ? extends V> multimap) {
124    this(keyComparator, valueComparator);
125    putAll(multimap);
126  }
127
128  /**
129   * {@inheritDoc}
130   *
131   * <p>Creates an empty {@code TreeSet} for a collection of values for one key.
132   *
133   * @return a new {@code TreeSet} containing a collection of values for one
134   *     key
135   */
136  @Override SortedSet<V> createCollection() {
137    return new TreeSet<V>(valueComparator);
138  }
139
140  /**
141   * Returns the comparator that orders the multimap keys.
142   */
143  public Comparator<? super K> keyComparator() {
144    return keyComparator;
145  }
146
147  @Override
148  public Comparator<? super V> valueComparator() {
149    return valueComparator;
150  }
151
152  /**
153   * {@inheritDoc}
154   *
155   * <p>Because a {@code TreeMultimap} has unique sorted keys, this method
156   * returns a {@link SortedSet}, instead of the {@link Set} specified in the
157   * {@link Multimap} interface.
158   */
159  @Override public SortedSet<K> keySet() {
160    return (SortedSet<K>) super.keySet();
161  }
162
163  /**
164   * {@inheritDoc}
165   *
166   * <p>Because a {@code TreeMultimap} has unique sorted keys, this method
167   * returns a {@link SortedMap}, instead of the {@link java.util.Map} specified
168   * in the {@link Multimap} interface.
169   */
170  @Override public SortedMap<K, Collection<V>> asMap() {
171    return (SortedMap<K, Collection<V>>) super.asMap();
172  }
173
174  /**
175   * @serialData key comparator, value comparator, number of distinct keys, and
176   *     then for each distinct key: the key, number of values for that key, and
177   *     key values
178   */
179  @GwtIncompatible("java.io.ObjectOutputStream")
180  private void writeObject(ObjectOutputStream stream) throws IOException {
181    stream.defaultWriteObject();
182    stream.writeObject(keyComparator());
183    stream.writeObject(valueComparator());
184    Serialization.writeMultimap(this, stream);
185  }
186
187  @GwtIncompatible("java.io.ObjectInputStream")
188  @SuppressWarnings("unchecked") // reading data stored by writeObject
189  private void readObject(ObjectInputStream stream)
190      throws IOException, ClassNotFoundException {
191    stream.defaultReadObject();
192    keyComparator = checkNotNull((Comparator<? super K>) stream.readObject());
193    valueComparator = checkNotNull((Comparator<? super V>) stream.readObject());
194    setMap(new TreeMap<K, Collection<V>>(keyComparator));
195    Serialization.populateMultimap(this, stream);
196  }
197
198  @GwtIncompatible("not needed in emulated source")
199  private static final long serialVersionUID = 0;
200}