001    /*
002     * Copyright (C) 2007 Google Inc.
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.Set;
030    import java.util.SortedMap;
031    import java.util.SortedSet;
032    import java.util.TreeMap;
033    import 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)
072    public 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      public Comparator<? super V> valueComparator() {
148        return valueComparator;
149      }
150    
151      /**
152       * {@inheritDoc}
153       *
154       * <p>Because a {@code TreeMultimap} has unique sorted keys, this method
155       * returns a {@link SortedSet}, instead of the {@link Set} specified in the
156       * {@link Multimap} interface.
157       */
158      @Override public SortedSet<K> keySet() {
159        return (SortedSet<K>) super.keySet();
160      }
161    
162      /**
163       * {@inheritDoc}
164       *
165       * <p>Because a {@code TreeMultimap} has unique sorted keys, this method
166       * returns a {@link SortedMap}, instead of the {@link java.util.Map} specified
167       * in the {@link Multimap} interface.
168       */
169      @Override public SortedMap<K, Collection<V>> asMap() {
170        return (SortedMap<K, Collection<V>>) super.asMap();
171      }
172    
173      /**
174       * @serialData key comparator, value comparator, number of distinct keys, and
175       *     then for each distinct key: the key, number of values for that key, and
176       *     key values
177       */
178      @GwtIncompatible("java.io.ObjectOutputStream")
179      private void writeObject(ObjectOutputStream stream) throws IOException {
180        stream.defaultWriteObject();
181        stream.writeObject(keyComparator());
182        stream.writeObject(valueComparator());
183        Serialization.writeMultimap(this, stream);
184      }
185    
186      @GwtIncompatible("java.io.ObjectInputStream")
187      @SuppressWarnings("unchecked") // reading data stored by writeObject
188      private void readObject(ObjectInputStream stream)
189          throws IOException, ClassNotFoundException {
190        stream.defaultReadObject();
191        keyComparator = checkNotNull((Comparator<? super K>) stream.readObject());
192        valueComparator = checkNotNull((Comparator<? super V>) stream.readObject());
193        setMap(new TreeMap<K, Collection<V>>(keyComparator));
194        Serialization.populateMultimap(this, stream);
195      }
196    
197      @GwtIncompatible("not needed in emulated source")
198      private static final long serialVersionUID = 0;
199    }