001 /*
002 * Copyright (C) 2008 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
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.primitives.Ints;
023
024 import java.io.Serializable;
025 import java.util.ArrayList;
026 import java.util.Arrays;
027 import java.util.Collection;
028 import java.util.Collections;
029 import java.util.Iterator;
030 import java.util.List;
031
032 import javax.annotation.Nullable;
033
034 /**
035 * An immutable hash-based multiset. Does not permit null elements.
036 *
037 * <p>Its iterator orders elements according to the first appearance of the
038 * element among the items passed to the factory method or builder. When the
039 * multiset contains multiple instances of an element, those instances are
040 * consecutive in the iteration order.
041 *
042 * <p>See the Guava User Guide article on <a href=
043 * "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained">
044 * immutable collections</a>.
045 *
046 * @author Jared Levy
047 * @author Louis Wasserman
048 * @since 2.0 (imported from Google Collections Library)
049 */
050 @GwtCompatible(serializable = true)
051 @SuppressWarnings("serial") // we're overriding default serialization
052 // TODO(user): write an efficient asList() implementation
053 public abstract 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.0 (source-compatible since 2.0)
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.0 (source-compatible since 2.0)
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.0 (source-compatible since 2.0)
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.0 (source-compatible since 2.0)
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.0 (source-compatible since 2.0)
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.0 (source-compatible since 2.0)
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.copyOf([2, 3, 1, 3])} yields a multiset
140 * with elements in the order {@code 2, 3, 3, 1}.
141 *
142 * @throws NullPointerException if any of {@code elements} is null
143 * @since 6.0
144 */
145 public static <E> ImmutableMultiset<E> copyOf(E[] elements) {
146 return copyOf(Arrays.asList(elements));
147 }
148
149 /**
150 * Returns an immutable multiset containing the given elements.
151 *
152 * <p>The multiset is ordered by the first occurrence of each element. For
153 * example, {@code ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3))} yields
154 * a multiset with elements in the order {@code 2, 3, 3, 1}.
155 *
156 * <p>Despite the method name, this method attempts to avoid actually copying
157 * the data when it is safe to do so. The exact circumstances under which a
158 * copy will or will not be performed are undocumented and subject to change.
159 *
160 * <p><b>Note:</b> Despite what the method name suggests, if {@code elements}
161 * is an {@code ImmutableMultiset}, no copy will actually be performed, and
162 * the given multiset itself will be returned.
163 *
164 * @throws NullPointerException if any of {@code elements} is null
165 */
166 public static <E> ImmutableMultiset<E> copyOf(
167 Iterable<? extends E> elements) {
168 if (elements instanceof ImmutableMultiset) {
169 @SuppressWarnings("unchecked") // all supported methods are covariant
170 ImmutableMultiset<E> result = (ImmutableMultiset<E>) elements;
171 if (!result.isPartialView()) {
172 return result;
173 }
174 }
175
176 Multiset<? extends E> multiset = (elements instanceof Multiset)
177 ? Multisets.cast(elements)
178 : LinkedHashMultiset.create(elements);
179
180 return copyOfInternal(multiset);
181 }
182
183 private static <E> ImmutableMultiset<E> copyOfInternal(E... elements) {
184 return copyOf(Arrays.asList(elements));
185 }
186
187 private static <E> ImmutableMultiset<E> copyOfInternal(
188 Multiset<? extends E> multiset) {
189 return copyFromEntries(multiset.entrySet());
190 }
191
192 static <E> ImmutableMultiset<E> copyFromEntries(
193 Collection<? extends Entry<? extends E>> entries) {
194 long size = 0;
195 ImmutableMap.Builder<E, Integer> builder = ImmutableMap.builder();
196 for (Entry<? extends E> entry : entries) {
197 int count = entry.getCount();
198 if (count > 0) {
199 // Since ImmutableMap.Builder throws an NPE if an element is null, no
200 // other null checks are needed.
201 builder.put(entry.getElement(), count);
202 size += count;
203 }
204 }
205
206 if (size == 0) {
207 return of();
208 }
209 return new RegularImmutableMultiset<E>(builder.build(), Ints.saturatedCast(size));
210 }
211
212 /**
213 * Returns an immutable multiset containing the given elements.
214 *
215 * <p>The multiset is ordered by the first occurrence of each element. For
216 * example,
217 * {@code ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3).iterator())}
218 * yields a multiset with elements in the order {@code 2, 3, 3, 1}.
219 *
220 * @throws NullPointerException if any of {@code elements} is null
221 */
222 public static <E> ImmutableMultiset<E> copyOf(
223 Iterator<? extends E> elements) {
224 Multiset<E> multiset = LinkedHashMultiset.create();
225 Iterators.addAll(multiset, elements);
226 return copyOfInternal(multiset);
227 }
228
229 ImmutableMultiset() {}
230
231 @Override public UnmodifiableIterator<E> iterator() {
232 final Iterator<Entry<E>> entryIterator = entrySet().iterator();
233 return new UnmodifiableIterator<E>() {
234 int remaining;
235 E element;
236
237 @Override
238 public boolean hasNext() {
239 return (remaining > 0) || entryIterator.hasNext();
240 }
241
242 @Override
243 public E next() {
244 if (remaining <= 0) {
245 Entry<E> entry = entryIterator.next();
246 element = entry.getElement();
247 remaining = entry.getCount();
248 }
249 remaining--;
250 return element;
251 }
252 };
253 }
254
255 @Override
256 public boolean contains(@Nullable Object object) {
257 return count(object) > 0;
258 }
259
260 @Override
261 public boolean containsAll(Collection<?> targets) {
262 return elementSet().containsAll(targets);
263 }
264
265 /**
266 * Guaranteed to throw an exception and leave the collection unmodified.
267 *
268 * @throws UnsupportedOperationException always
269 */
270 @Override
271 public final int add(E element, int occurrences) {
272 throw new UnsupportedOperationException();
273 }
274
275 /**
276 * Guaranteed to throw an exception and leave the collection unmodified.
277 *
278 * @throws UnsupportedOperationException always
279 */
280 @Override
281 public final int remove(Object element, int occurrences) {
282 throw new UnsupportedOperationException();
283 }
284
285 /**
286 * Guaranteed to throw an exception and leave the collection unmodified.
287 *
288 * @throws UnsupportedOperationException always
289 */
290 @Override
291 public final int setCount(E element, int count) {
292 throw new UnsupportedOperationException();
293 }
294
295 /**
296 * Guaranteed to throw an exception and leave the collection unmodified.
297 *
298 * @throws UnsupportedOperationException always
299 */
300 @Override
301 public final boolean setCount(E element, int oldCount, int newCount) {
302 throw new UnsupportedOperationException();
303 }
304
305 @Override public boolean equals(@Nullable Object object) {
306 if (object == this) {
307 return true;
308 }
309 if (object instanceof Multiset) {
310 Multiset<?> that = (Multiset<?>) object;
311 if (this.size() != that.size()) {
312 return false;
313 }
314 for (Entry<?> entry : that.entrySet()) {
315 if (count(entry.getElement()) != entry.getCount()) {
316 return false;
317 }
318 }
319 return true;
320 }
321 return false;
322 }
323
324 @Override public int hashCode() {
325 return Sets.hashCodeImpl(entrySet());
326 }
327
328 @Override public String toString() {
329 return entrySet().toString();
330 }
331
332 private transient ImmutableSet<Entry<E>> entrySet;
333
334 @Override
335 public final ImmutableSet<Entry<E>> entrySet() {
336 ImmutableSet<Entry<E>> es = entrySet;
337 return (es == null) ? (entrySet = createEntrySet()) : es;
338 }
339
340 abstract ImmutableSet<Entry<E>> createEntrySet();
341
342 abstract class EntrySet extends ImmutableSet<Entry<E>> {
343 @Override
344 boolean isPartialView() {
345 return ImmutableMultiset.this.isPartialView();
346 }
347
348 @Override
349 public boolean contains(Object o) {
350 if (o instanceof Entry) {
351 Entry<?> entry = (Entry<?>) o;
352 if (entry.getCount() <= 0) {
353 return false;
354 }
355 int count = count(entry.getElement());
356 return count == entry.getCount();
357 }
358 return false;
359 }
360
361 /*
362 * TODO(hhchan): Revert once we have a separate, manual emulation of this
363 * class.
364 */
365 @Override
366 public Object[] toArray() {
367 Object[] newArray = new Object[size()];
368 return toArray(newArray);
369 }
370
371 /*
372 * TODO(hhchan): Revert once we have a separate, manual emulation of this
373 * class.
374 */
375 @Override
376 public <T> T[] toArray(T[] other) {
377 int size = size();
378 if (other.length < size) {
379 other = ObjectArrays.newArray(other, size);
380 } else if (other.length > size) {
381 other[size] = null;
382 }
383
384 // Writes will produce ArrayStoreException when the toArray() doc requires
385 Object[] otherAsObjectArray = other;
386 int index = 0;
387 for (Entry<?> element : this) {
388 otherAsObjectArray[index++] = element;
389 }
390 return other;
391 }
392
393 @Override
394 public int hashCode() {
395 return ImmutableMultiset.this.hashCode();
396 }
397
398 // We can't label this with @Override, because it doesn't override anything
399 // in the GWT emulated version.
400 // TODO(cpovirk): try making all copies of this method @GwtIncompatible instead
401 Object writeReplace() {
402 return new EntrySetSerializedForm<E>(ImmutableMultiset.this);
403 }
404
405 private static final long serialVersionUID = 0;
406 }
407
408 static class EntrySetSerializedForm<E> implements Serializable {
409 final ImmutableMultiset<E> multiset;
410
411 EntrySetSerializedForm(ImmutableMultiset<E> multiset) {
412 this.multiset = multiset;
413 }
414
415 Object readResolve() {
416 return multiset.entrySet();
417 }
418 }
419
420 private static class SerializedForm implements Serializable {
421 final Object[] elements;
422 final int[] counts;
423
424 SerializedForm(Multiset<?> multiset) {
425 int distinct = multiset.entrySet().size();
426 elements = new Object[distinct];
427 counts = new int[distinct];
428 int i = 0;
429 for (Entry<?> entry : multiset.entrySet()) {
430 elements[i] = entry.getElement();
431 counts[i] = entry.getCount();
432 i++;
433 }
434 }
435
436 Object readResolve() {
437 LinkedHashMultiset<Object> multiset =
438 LinkedHashMultiset.create(elements.length);
439 for (int i = 0; i < elements.length; i++) {
440 multiset.add(elements[i], counts[i]);
441 }
442 return ImmutableMultiset.copyOf(multiset);
443 }
444
445 private static final long serialVersionUID = 0;
446 }
447
448 // We can't label this with @Override, because it doesn't override anything
449 // in the GWT emulated version.
450 Object writeReplace() {
451 return new SerializedForm(this);
452 }
453
454 /**
455 * Returns a new builder. The generated builder is equivalent to the builder
456 * created by the {@link Builder} constructor.
457 */
458 public static <E> Builder<E> builder() {
459 return new Builder<E>();
460 }
461
462 /**
463 * A builder for creating immutable multiset instances, especially {@code
464 * public static final} multisets ("constant multisets"). Example:
465 * <pre> {@code
466 *
467 * public static final ImmutableMultiset<Bean> BEANS =
468 * new ImmutableMultiset.Builder<Bean>()
469 * .addCopies(Bean.COCOA, 4)
470 * .addCopies(Bean.GARDEN, 6)
471 * .addCopies(Bean.RED, 8)
472 * .addCopies(Bean.BLACK_EYED, 10)
473 * .build();}</pre>
474 *
475 * Builder instances can be reused; it is safe to call {@link #build} multiple
476 * times to build multiple multisets in series.
477 *
478 * @since 2.0 (imported from Google Collections Library)
479 */
480 public static class Builder<E> extends ImmutableCollection.Builder<E> {
481 final Multiset<E> contents;
482
483 /**
484 * Creates a new builder. The returned builder is equivalent to the builder
485 * generated by {@link ImmutableMultiset#builder}.
486 */
487 public Builder() {
488 this(LinkedHashMultiset.<E>create());
489 }
490
491 Builder(Multiset<E> contents) {
492 this.contents = contents;
493 }
494
495 /**
496 * Adds {@code element} to the {@code ImmutableMultiset}.
497 *
498 * @param element the element to add
499 * @return this {@code Builder} object
500 * @throws NullPointerException if {@code element} is null
501 */
502 @Override public Builder<E> add(E element) {
503 contents.add(checkNotNull(element));
504 return this;
505 }
506
507 /**
508 * Adds a number of occurrences of an element to this {@code
509 * ImmutableMultiset}.
510 *
511 * @param element the element to add
512 * @param occurrences the number of occurrences of the element to add. May
513 * be zero, in which case no change will be made.
514 * @return this {@code Builder} object
515 * @throws NullPointerException if {@code element} is null
516 * @throws IllegalArgumentException if {@code occurrences} is negative, or
517 * if this operation would result in more than {@link Integer#MAX_VALUE}
518 * occurrences of the element
519 */
520 public Builder<E> addCopies(E element, int occurrences) {
521 contents.add(checkNotNull(element), occurrences);
522 return this;
523 }
524
525 /**
526 * Adds or removes the necessary occurrences of an element such that the
527 * element attains the desired count.
528 *
529 * @param element the element to add or remove occurrences of
530 * @param count the desired count of the element in this multiset
531 * @return this {@code Builder} object
532 * @throws NullPointerException if {@code element} is null
533 * @throws IllegalArgumentException if {@code count} is negative
534 */
535 public Builder<E> setCount(E element, int count) {
536 contents.setCount(checkNotNull(element), count);
537 return this;
538 }
539
540 /**
541 * Adds each element of {@code elements} to the {@code ImmutableMultiset}.
542 *
543 * @param elements the elements to add
544 * @return this {@code Builder} object
545 * @throws NullPointerException if {@code elements} is null or contains a
546 * null element
547 */
548 @Override public Builder<E> add(E... elements) {
549 super.add(elements);
550 return this;
551 }
552
553 /**
554 * Adds each element of {@code elements} to the {@code ImmutableMultiset}.
555 *
556 * @param elements the {@code Iterable} to add to the {@code
557 * ImmutableMultiset}
558 * @return this {@code Builder} object
559 * @throws NullPointerException if {@code elements} is null or contains a
560 * null element
561 */
562 @Override public Builder<E> addAll(Iterable<? extends E> elements) {
563 if (elements instanceof Multiset) {
564 Multiset<? extends E> multiset = Multisets.cast(elements);
565 for (Entry<? extends E> entry : multiset.entrySet()) {
566 addCopies(entry.getElement(), entry.getCount());
567 }
568 } else {
569 super.addAll(elements);
570 }
571 return this;
572 }
573
574 /**
575 * Adds each element of {@code elements} to the {@code ImmutableMultiset}.
576 *
577 * @param elements the elements to add to the {@code ImmutableMultiset}
578 * @return this {@code Builder} object
579 * @throws NullPointerException if {@code elements} is null or contains a
580 * null element
581 */
582 @Override public Builder<E> addAll(Iterator<? extends E> elements) {
583 super.addAll(elements);
584 return this;
585 }
586
587 /**
588 * Returns a newly-created {@code ImmutableMultiset} based on the contents
589 * of the {@code Builder}.
590 */
591 @Override public ImmutableMultiset<E> build() {
592 return copyOf(contents);
593 }
594 }
595 }