001 /*
002 * Copyright (C) 2008 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 import com.google.common.collect.Serialization.FieldSetter;
024 import com.google.common.primitives.Ints;
025
026 import java.io.IOException;
027 import java.io.InvalidObjectException;
028 import java.io.ObjectInputStream;
029 import java.io.ObjectOutputStream;
030 import java.util.ArrayList;
031 import java.util.Arrays;
032 import java.util.Collections;
033 import java.util.Iterator;
034 import java.util.List;
035 import java.util.Map;
036 import java.util.Set;
037
038 import javax.annotation.Nullable;
039
040 /**
041 * An immutable hash-based multiset. Does not permit null elements.
042 *
043 * <p>Its iterator orders elements according to the first appearance of the
044 * element among the items passed to the factory method or builder. When the
045 * multiset contains multiple instances of an element, those instances are
046 * consecutive in the iteration order.
047 *
048 * @author Jared Levy
049 * @since 2 (imported from Google Collections Library)
050 */
051 @GwtCompatible(serializable = true, emulated = true)
052 // TODO(user): write an efficient asList() implementation
053 public class ImmutableMultiset<E> extends ImmutableCollection<E>
054 implements Multiset<E> {
055
056 /**
057 * Returns the empty immutable multiset.
058 */
059 @SuppressWarnings("unchecked") // all supported methods are covariant
060 public static <E> ImmutableMultiset<E> of() {
061 return (ImmutableMultiset<E>) EmptyImmutableMultiset.INSTANCE;
062 }
063
064 /**
065 * Returns an immutable multiset containing a single element.
066 *
067 * @throws NullPointerException if {@code element} is null
068 * @since 6 (source-compatible since release 2)
069 */
070 @SuppressWarnings("unchecked") // generic array created but never written
071 public static <E> ImmutableMultiset<E> of(E element) {
072 return copyOfInternal(element);
073 }
074
075 /**
076 * Returns an immutable multiset containing the given elements, in order.
077 *
078 * @throws NullPointerException if any element is null
079 * @since 6 (source-compatible since release 2)
080 */
081 @SuppressWarnings("unchecked") //
082 public static <E> ImmutableMultiset<E> of(E e1, E e2) {
083 return copyOfInternal(e1, e2);
084 }
085
086 /**
087 * Returns an immutable multiset containing the given elements, in order.
088 *
089 * @throws NullPointerException if any element is null
090 * @since 6 (source-compatible since release 2)
091 */
092 @SuppressWarnings("unchecked") //
093 public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3) {
094 return copyOfInternal(e1, e2, e3);
095 }
096
097 /**
098 * Returns an immutable multiset containing the given elements, in order.
099 *
100 * @throws NullPointerException if any element is null
101 * @since 6 (source-compatible since release 2)
102 */
103 @SuppressWarnings("unchecked") //
104 public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3, E e4) {
105 return copyOfInternal(e1, e2, e3, e4);
106 }
107
108 /**
109 * Returns an immutable multiset containing the given elements, in order.
110 *
111 * @throws NullPointerException if any element is null
112 * @since 6 (source-compatible since release 2)
113 */
114 @SuppressWarnings("unchecked") //
115 public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3, E e4, E e5) {
116 return copyOfInternal(e1, e2, e3, e4, e5);
117 }
118
119 /**
120 * Returns an immutable multiset containing the given elements, in order.
121 *
122 * @throws NullPointerException if any element is null
123 * @since 6 (source-compatible since release 2)
124 */
125 @SuppressWarnings("unchecked") //
126 public static <E> ImmutableMultiset<E> of(
127 E e1, E e2, E e3, E e4, E e5, E e6, E... others) {
128 int size = others.length + 6;
129 List<E> all = new ArrayList<E>(size);
130 Collections.addAll(all, e1, e2, e3, e4, e5, e6);
131 Collections.addAll(all, others);
132 return copyOf(all);
133 }
134
135 /**
136 * Returns an immutable multiset containing the given elements.
137 *
138 * <p>The multiset is ordered by the first occurrence of each element. For
139 * example, {@code ImmutableMultiset.of(2, 3, 1, 3)} yields a multiset with
140 * elements in the order {@code 2, 3, 3, 1}.
141 *
142 * @throws NullPointerException if any of {@code elements} is null
143 * @deprecated use {@link #copyOf(Object[])}. <b>This method is scheduled for
144 * deletion in January 2012.</b>
145 * @since 2 (changed from varargs in release 6)
146 */
147 @Deprecated
148 public static <E> ImmutableMultiset<E> of(E[] elements) {
149 return copyOf(Arrays.asList(elements));
150 }
151
152 /**
153 * Returns an immutable multiset containing the given elements.
154 *
155 * <p>The multiset is ordered by the first occurrence of each element. For
156 * example, {@code ImmutableMultiset.copyOf([2, 3, 1, 3])} yields a multiset
157 * with elements in the order {@code 2, 3, 3, 1}.
158 *
159 * @throws NullPointerException if any of {@code elements} is null
160 * @since 6
161 */
162 public static <E> ImmutableMultiset<E> copyOf(E[] elements) {
163 return copyOf(Arrays.asList(elements));
164 }
165
166 /**
167 * Returns an immutable multiset containing the given elements.
168 *
169 * <p>The multiset is ordered by the first occurrence of each element. For
170 * example, {@code ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3))} yields
171 * a multiset with elements in the order {@code 2, 3, 3, 1}.
172 *
173 * <p>Despite the method name, this method attempts to avoid actually copying
174 * the data when it is safe to do so. The exact circumstances under which a
175 * copy will or will not be performed are undocumented and subject to change.
176 *
177 * <p><b>Note:</b> Despite what the method name suggests, if {@code elements}
178 * is an {@code ImmutableMultiset}, no copy will actually be performed, and
179 * the given multiset itself will be returned.
180 *
181 * @throws NullPointerException if any of {@code elements} is null
182 */
183 public static <E> ImmutableMultiset<E> copyOf(
184 Iterable<? extends E> elements) {
185 if (elements instanceof ImmutableMultiset) {
186 @SuppressWarnings("unchecked") // all supported methods are covariant
187 ImmutableMultiset<E> result = (ImmutableMultiset<E>) elements;
188 if (!result.isPartialView()) {
189 return result;
190 }
191 }
192
193 Multiset<? extends E> multiset = (elements instanceof Multiset)
194 ? Multisets.cast(elements)
195 : LinkedHashMultiset.create(elements);
196
197 return copyOfInternal(multiset);
198 }
199
200 private static <E> ImmutableMultiset<E> copyOfInternal(E... elements) {
201 return copyOf(Arrays.asList(elements));
202 }
203
204 private static <E> ImmutableMultiset<E> copyOfInternal(
205 Multiset<? extends E> multiset) {
206 long size = 0;
207 ImmutableMap.Builder<E, Integer> builder = ImmutableMap.builder();
208
209 for (Entry<? extends E> entry : multiset.entrySet()) {
210 int count = entry.getCount();
211 if (count > 0) {
212 // Since ImmutableMap.Builder throws an NPE if an element is null, no
213 // other null checks are needed.
214 builder.put(entry.getElement(), count);
215 size += count;
216 }
217 }
218
219 if (size == 0) {
220 return of();
221 }
222 return new ImmutableMultiset<E>(builder.build(), Ints.saturatedCast(size));
223 }
224
225 /**
226 * Returns an immutable multiset containing the given elements.
227 *
228 * <p>The multiset is ordered by the first occurrence of each element. For
229 * example,
230 * {@code ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3).iterator())}
231 * yields a multiset with elements in the order {@code 2, 3, 3, 1}.
232 *
233 * @throws NullPointerException if any of {@code elements} is null
234 */
235 public static <E> ImmutableMultiset<E> copyOf(
236 Iterator<? extends E> elements) {
237 Multiset<E> multiset = LinkedHashMultiset.create();
238 Iterators.addAll(multiset, elements);
239 return copyOfInternal(multiset);
240 }
241
242 private final transient ImmutableMap<E, Integer> map;
243 private final transient int size;
244
245 // These constants allow the deserialization code to set final fields. This
246 // holder class makes sure they are not initialized unless an instance is
247 // deserialized.
248 @GwtIncompatible("java serialization is not supported.")
249 @SuppressWarnings("unchecked")
250 // eclipse doesn't like the raw types here, but they're harmless
251 private static class FieldSettersHolder {
252 static final FieldSetter<ImmutableMultiset> MAP_FIELD_SETTER
253 = Serialization.getFieldSetter(ImmutableMultiset.class, "map");
254 static final FieldSetter<ImmutableMultiset> SIZE_FIELD_SETTER
255 = Serialization.getFieldSetter(ImmutableMultiset.class, "size");
256 }
257
258 ImmutableMultiset(ImmutableMap<E, Integer> map, int size) {
259 this.map = map;
260 this.size = size;
261 }
262
263 @Override boolean isPartialView() {
264 return map.isPartialView();
265 }
266
267 public int count(@Nullable Object element) {
268 Integer value = map.get(element);
269 return (value == null) ? 0 : value;
270 }
271
272 @Override public UnmodifiableIterator<E> iterator() {
273 final Iterator<Map.Entry<E, Integer>> mapIterator
274 = map.entrySet().iterator();
275
276 return new UnmodifiableIterator<E>() {
277 int remaining;
278 E element;
279
280 public boolean hasNext() {
281 return (remaining > 0) || mapIterator.hasNext();
282 }
283
284 public E next() {
285 if (remaining <= 0) {
286 Map.Entry<E, Integer> entry = mapIterator.next();
287 element = entry.getKey();
288 remaining = entry.getValue();
289 }
290 remaining--;
291 return element;
292 }
293 };
294 }
295
296 public int size() {
297 return size;
298 }
299
300 @Override public boolean contains(@Nullable Object element) {
301 return map.containsKey(element);
302 }
303
304 /**
305 * Guaranteed to throw an exception and leave the collection unmodified.
306 *
307 * @throws UnsupportedOperationException always
308 */
309 public int add(E element, int occurrences) {
310 throw new UnsupportedOperationException();
311 }
312
313 /**
314 * Guaranteed to throw an exception and leave the collection unmodified.
315 *
316 * @throws UnsupportedOperationException always
317 */
318 public int remove(Object element, int occurrences) {
319 throw new UnsupportedOperationException();
320 }
321
322 /**
323 * Guaranteed to throw an exception and leave the collection unmodified.
324 *
325 * @throws UnsupportedOperationException always
326 */
327 public int setCount(E element, int count) {
328 throw new UnsupportedOperationException();
329 }
330
331 /**
332 * Guaranteed to throw an exception and leave the collection unmodified.
333 *
334 * @throws UnsupportedOperationException always
335 */
336 public boolean setCount(E element, int oldCount, int newCount) {
337 throw new UnsupportedOperationException();
338 }
339
340 @Override public boolean equals(@Nullable Object object) {
341 if (object == this) {
342 return true;
343 }
344 if (object instanceof Multiset) {
345 Multiset<?> that = (Multiset<?>) object;
346 if (this.size() != that.size()) {
347 return false;
348 }
349 for (Entry<?> entry : that.entrySet()) {
350 if (count(entry.getElement()) != entry.getCount()) {
351 return false;
352 }
353 }
354 return true;
355 }
356 return false;
357 }
358
359 @Override public int hashCode() {
360 // could cache this, but not considered worthwhile to do so
361 return map.hashCode();
362 }
363
364 @Override public String toString() {
365 return entrySet().toString();
366 }
367
368 public Set<E> elementSet() {
369 return map.keySet();
370 }
371
372 private transient ImmutableSet<Entry<E>> entrySet;
373
374 public Set<Entry<E>> entrySet() {
375 ImmutableSet<Entry<E>> es = entrySet;
376 return (es == null) ? (entrySet = new EntrySet<E>(this)) : es;
377 }
378
379 private static class EntrySet<E> extends ImmutableSet<Entry<E>> {
380 final ImmutableMultiset<E> multiset;
381
382 public EntrySet(ImmutableMultiset<E> multiset) {
383 this.multiset = multiset;
384 }
385
386 @Override public UnmodifiableIterator<Entry<E>> iterator() {
387 final Iterator<Map.Entry<E, Integer>> mapIterator
388 = multiset.map.entrySet().iterator();
389 return new UnmodifiableIterator<Entry<E>>() {
390 public boolean hasNext() {
391 return mapIterator.hasNext();
392 }
393 public Entry<E> next() {
394 Map.Entry<E, Integer> mapEntry = mapIterator.next();
395 return
396 Multisets.immutableEntry(mapEntry.getKey(), mapEntry.getValue());
397 }
398 };
399 }
400
401 public int size() {
402 return multiset.map.size();
403 }
404
405 @Override boolean isPartialView() {
406 return multiset.isPartialView();
407 }
408
409 @Override public boolean contains(Object o) {
410 if (o instanceof Entry) {
411 Entry<?> entry = (Entry<?>) o;
412 if (entry.getCount() <= 0) {
413 return false;
414 }
415 int count = multiset.count(entry.getElement());
416 return count == entry.getCount();
417 }
418 return false;
419 }
420
421 // TODO(hhchan): Revert once this class is emulated in GWT.
422 @Override public Object[] toArray() {
423 Object[] newArray = new Object[size()];
424 return toArray(newArray);
425 }
426
427 // TODO(hhchan): Revert once this class is emulated in GWT.
428 @Override public <T> T[] toArray(T[] other) {
429 int size = size();
430 if (other.length < size) {
431 other = ObjectArrays.newArray(other, size);
432 } else if (other.length > size) {
433 other[size] = null;
434 }
435
436 // Writes will produce ArrayStoreException when the toArray() doc requires
437 Object[] otherAsObjectArray = other;
438 int index = 0;
439 for (Entry<?> element : this) {
440 otherAsObjectArray[index++] = element;
441 }
442 return other;
443 }
444
445 @Override public int hashCode() {
446 return multiset.map.hashCode();
447 }
448
449 @GwtIncompatible("not needed in emulated source.")
450 @Override Object writeReplace() {
451 return this;
452 }
453
454 private static final long serialVersionUID = 0;
455 }
456
457 /**
458 * @serialData the number of distinct elements, the first element, its count,
459 * the second element, its count, and so on
460 */
461 @GwtIncompatible("java.io.ObjectOutputStream")
462 private void writeObject(ObjectOutputStream stream) throws IOException {
463 stream.defaultWriteObject();
464 Serialization.writeMultiset(this, stream);
465 }
466
467 @GwtIncompatible("java.io.ObjectInputStream")
468 private void readObject(ObjectInputStream stream)
469 throws IOException, ClassNotFoundException {
470 stream.defaultReadObject();
471 int entryCount = stream.readInt();
472 ImmutableMap.Builder<E, Integer> builder = ImmutableMap.builder();
473 long tmpSize = 0;
474 for (int i = 0; i < entryCount; i++) {
475 @SuppressWarnings("unchecked") // reading data stored by writeMultiset
476 E element = (E) stream.readObject();
477 int count = stream.readInt();
478 if (count <= 0) {
479 throw new InvalidObjectException("Invalid count " + count);
480 }
481 builder.put(element, count);
482 tmpSize += count;
483 }
484
485 FieldSettersHolder.MAP_FIELD_SETTER.set(this, builder.build());
486 FieldSettersHolder.SIZE_FIELD_SETTER.set(this, Ints.saturatedCast(tmpSize));
487 }
488
489 @GwtIncompatible("java serialization not supported.")
490 @Override Object writeReplace() {
491 return this;
492 }
493
494 private static final long serialVersionUID = 0;
495
496 /**
497 * Returns a new builder. The generated builder is equivalent to the builder
498 * created by the {@link Builder} constructor.
499 */
500 public static <E> Builder<E> builder() {
501 return new Builder<E>();
502 }
503
504 /**
505 * A builder for creating immutable multiset instances, especially {@code
506 * public static final} multisets ("constant multisets"). Example:
507 * <pre> {@code
508 *
509 * public static final ImmutableMultiset<Bean> BEANS =
510 * new ImmutableMultiset.Builder<Bean>()
511 * .addCopies(Bean.COCOA, 4)
512 * .addCopies(Bean.GARDEN, 6)
513 * .addCopies(Bean.RED, 8)
514 * .addCopies(Bean.BLACK_EYED, 10)
515 * .build();}</pre>
516 *
517 * Builder instances can be reused; it is safe to call {@link #build} multiple
518 * times to build multiple multisets in series. Each multiset is a superset of
519 * the multiset created before it.
520 *
521 * @since 2 (imported from Google Collections Library)
522 */
523 public static final class Builder<E> extends ImmutableCollection.Builder<E> {
524 private final Multiset<E> contents = LinkedHashMultiset.create();
525
526 /**
527 * Creates a new builder. The returned builder is equivalent to the builder
528 * generated by {@link ImmutableMultiset#builder}.
529 */
530 public Builder() {}
531
532 /**
533 * Adds {@code element} to the {@code ImmutableMultiset}.
534 *
535 * @param element the element to add
536 * @return this {@code Builder} object
537 * @throws NullPointerException if {@code element} is null
538 */
539 @Override public Builder<E> add(E element) {
540 contents.add(checkNotNull(element));
541 return this;
542 }
543
544 /**
545 * Adds a number of occurrences of an element to this {@code
546 * ImmutableMultiset}.
547 *
548 * @param element the element to add
549 * @param occurrences the number of occurrences of the element to add. May
550 * be zero, in which case no change will be made.
551 * @return this {@code Builder} object
552 * @throws NullPointerException if {@code element} is null
553 * @throws IllegalArgumentException if {@code occurrences} is negative, or
554 * if this operation would result in more than {@link Integer#MAX_VALUE}
555 * occurrences of the element
556 */
557 public Builder<E> addCopies(E element, int occurrences) {
558 contents.add(checkNotNull(element), occurrences);
559 return this;
560 }
561
562 /**
563 * Adds or removes the necessary occurrences of an element such that the
564 * element attains the desired count.
565 *
566 * @param element the element to add or remove occurrences of
567 * @param count the desired count of the element in this multiset
568 * @return this {@code Builder} object
569 * @throws NullPointerException if {@code element} is null
570 * @throws IllegalArgumentException if {@code count} is negative
571 */
572 public Builder<E> setCount(E element, int count) {
573 contents.setCount(checkNotNull(element), count);
574 return this;
575 }
576
577 /**
578 * Adds each element of {@code elements} to the {@code ImmutableMultiset}.
579 *
580 * @param elements the elements to add
581 * @return this {@code Builder} object
582 * @throws NullPointerException if {@code elements} is null or contains a
583 * null element
584 */
585 @Override public Builder<E> add(E... elements) {
586 super.add(elements);
587 return this;
588 }
589
590 /**
591 * Adds each element of {@code elements} to the {@code ImmutableMultiset}.
592 *
593 * @param elements the {@code Iterable} to add to the {@code
594 * ImmutableMultiset}
595 * @return this {@code Builder} object
596 * @throws NullPointerException if {@code elements} is null or contains a
597 * null element
598 */
599 @Override public Builder<E> addAll(Iterable<? extends E> elements) {
600 if (elements instanceof Multiset) {
601 Multiset<? extends E> multiset = Multisets.cast(elements);
602 for (Entry<? extends E> entry : multiset.entrySet()) {
603 addCopies(entry.getElement(), entry.getCount());
604 }
605 } else {
606 super.addAll(elements);
607 }
608 return this;
609 }
610
611 /**
612 * Adds each element of {@code elements} to the {@code ImmutableMultiset}.
613 *
614 * @param elements the elements to add to the {@code ImmutableMultiset}
615 * @return this {@code Builder} object
616 * @throws NullPointerException if {@code elements} is null or contains a
617 * null element
618 */
619 @Override public Builder<E> addAll(Iterator<? extends E> elements) {
620 super.addAll(elements);
621 return this;
622 }
623
624 /**
625 * Returns a newly-created {@code ImmutableMultiset} based on the contents
626 * of the {@code Builder}.
627 */
628 @Override public ImmutableMultiset<E> build() {
629 return copyOf(contents);
630 }
631 }
632 }