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>(
210 builder.build(), Ints.saturatedCast(size));
211 }
212
213 /**
214 * Returns an immutable multiset containing the given elements.
215 *
216 * <p>The multiset is ordered by the first occurrence of each element. For
217 * example,
218 * {@code ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3).iterator())}
219 * yields a multiset with elements in the order {@code 2, 3, 3, 1}.
220 *
221 * @throws NullPointerException if any of {@code elements} is null
222 */
223 public static <E> ImmutableMultiset<E> copyOf(
224 Iterator<? extends E> elements) {
225 Multiset<E> multiset = LinkedHashMultiset.create();
226 Iterators.addAll(multiset, elements);
227 return copyOfInternal(multiset);
228 }
229
230 ImmutableMultiset() {}
231
232
233 @Override
234 public UnmodifiableIterator<E> iterator() {
235 final Iterator<Entry<E>> entryIterator = entrySet().iterator();
236 return new UnmodifiableIterator<E>() {
237 int remaining;
238 E element;
239
240 public boolean hasNext() {
241 return (remaining > 0) || entryIterator.hasNext();
242 }
243
244 public E next() {
245 if (remaining <= 0) {
246 Entry<E> entry = entryIterator.next();
247 element = entry.getElement();
248 remaining = entry.getCount();
249 }
250 remaining--;
251 return element;
252 }
253 };
254 }
255
256
257 @Override
258 public boolean contains(@Nullable Object object) {
259 return count(object) > 0;
260 }
261
262
263 @Override
264 public boolean containsAll(Collection<?> targets) {
265 return elementSet().containsAll(targets);
266 }
267
268 /**
269 * Guaranteed to throw an exception and leave the collection unmodified.
270 *
271 * @throws UnsupportedOperationException always
272 */
273 public final int add(E element, int occurrences) {
274 throw new UnsupportedOperationException();
275 }
276
277 /**
278 * Guaranteed to throw an exception and leave the collection unmodified.
279 *
280 * @throws UnsupportedOperationException always
281 */
282 public final int remove(Object element, int occurrences) {
283 throw new UnsupportedOperationException();
284 }
285
286 /**
287 * Guaranteed to throw an exception and leave the collection unmodified.
288 *
289 * @throws UnsupportedOperationException always
290 */
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 public final boolean setCount(E element, int oldCount, int newCount) {
301 throw new UnsupportedOperationException();
302 }
303
304
305 @Override
306 public boolean equals(@Nullable Object object) {
307 if (object == this) {
308 return true;
309 }
310 if (object instanceof Multiset) {
311 Multiset<?> that = (Multiset<?>) object;
312 if (this.size() != that.size()) {
313 return false;
314 }
315 for (Entry<?> entry : that.entrySet()) {
316 if (count(entry.getElement()) != entry.getCount()) {
317 return false;
318 }
319 }
320 return true;
321 }
322 return false;
323 }
324
325
326 @Override
327 public int hashCode() {
328 return Sets.hashCodeImpl(entrySet());
329 }
330
331
332 @Override
333 public String toString() {
334 return entrySet().toString();
335 }
336
337 private transient ImmutableSet<Entry<E>> entrySet;
338
339
340 public ImmutableSet<Entry<E>> entrySet() {
341 ImmutableSet<Entry<E>> es = entrySet;
342 return (es == null) ? (entrySet = createEntrySet()) : es;
343 }
344
345 abstract ImmutableSet<Entry<E>> createEntrySet();
346
347 abstract class EntrySet extends ImmutableSet<Entry<E>> {
348
349 @Override
350 boolean isPartialView() {
351 return ImmutableMultiset.this.isPartialView();
352 }
353
354
355 @Override
356 public boolean contains(Object o) {
357 if (o instanceof Entry) {
358 Entry<?> entry = (Entry<?>) o;
359 if (entry.getCount() <= 0) {
360 return false;
361 }
362 int count = count(entry.getElement());
363 return count == entry.getCount();
364 }
365 return false;
366 }
367
368 /*
369 * TODO(hhchan): Revert once we have a separate, manual emulation of this
370 * class.
371 */
372
373 @Override
374 public Object[] toArray() {
375 Object[] newArray = new Object[size()];
376 return toArray(newArray);
377 }
378
379 /*
380 * TODO(hhchan): Revert once we have a separate, manual emulation of this
381 * class.
382 */
383
384 @Override
385 public <T> T[] toArray(T[] other) {
386 int size = size();
387 if (other.length < size) {
388 other = ObjectArrays.newArray(other, size);
389 } else if (other.length > size) {
390 other[size] = null;
391 }
392
393 // Writes will produce ArrayStoreException when the toArray() doc requires
394 Object[] otherAsObjectArray = other;
395 int index = 0;
396 for (Entry<?> element : this) {
397 otherAsObjectArray[index++] = element;
398 }
399 return other;
400 }
401
402
403 @Override
404 public int hashCode() {
405 return ImmutableMultiset.this.hashCode();
406 }
407
408 // We can't label this with @Override, because it doesn't override anything
409 // in the GWT emulated version.
410 // TODO(cpovirk): try making all copies of this method @GwtIncompatible instead
411
412 @Override
413 Object writeReplace() {
414 return new EntrySetSerializedForm<E>(ImmutableMultiset.this);
415 }
416
417 private static final long serialVersionUID = 0;
418 }
419
420 static class EntrySetSerializedForm<E> implements Serializable {
421 final ImmutableMultiset<E> multiset;
422
423 EntrySetSerializedForm(ImmutableMultiset<E> multiset) {
424 this.multiset = multiset;
425 }
426
427 Object readResolve() {
428 return multiset.entrySet();
429 }
430 }
431
432 private static class SerializedForm implements Serializable {
433 final Object[] elements;
434 final int[] counts;
435
436 SerializedForm(Multiset<?> multiset) {
437 int distinct = multiset.entrySet().size();
438 elements = new Object[distinct];
439 counts = new int[distinct];
440 int i = 0;
441 for (Entry<?> entry : multiset.entrySet()) {
442 elements[i] = entry.getElement();
443 counts[i] = entry.getCount();
444 i++;
445 }
446 }
447
448 Object readResolve() {
449 LinkedHashMultiset<Object> multiset =
450 LinkedHashMultiset.create(elements.length);
451 for (int i = 0; i < elements.length; i++) {
452 multiset.add(elements[i], counts[i]);
453 }
454 return ImmutableMultiset.copyOf(multiset);
455 }
456
457 private static final long serialVersionUID = 0;
458 }
459
460 // We can't label this with @Override, because it doesn't override anything
461 // in the GWT emulated version.
462
463 @Override
464 Object writeReplace() {
465 return new SerializedForm(this);
466 }
467
468 /**
469 * Returns a new builder. The generated builder is equivalent to the builder
470 * created by the {@link Builder} constructor.
471 */
472 public static <E> Builder<E> builder() {
473 return new Builder<E>();
474 }
475
476 /**
477 * A builder for creating immutable multiset instances, especially {@code
478 * public static final} multisets ("constant multisets"). Example:
479 * <pre> {@code
480 *
481 * public static final ImmutableMultiset<Bean> BEANS =
482 * new ImmutableMultiset.Builder<Bean>()
483 * .addCopies(Bean.COCOA, 4)
484 * .addCopies(Bean.GARDEN, 6)
485 * .addCopies(Bean.RED, 8)
486 * .addCopies(Bean.BLACK_EYED, 10)
487 * .build();}</pre>
488 *
489 * Builder instances can be reused; it is safe to call {@link #build} multiple
490 * times to build multiple multisets in series.
491 *
492 * @since 2.0 (imported from Google Collections Library)
493 */
494 public static class Builder<E> extends ImmutableCollection.Builder<E> {
495 final Multiset<E> contents;
496
497 /**
498 * Creates a new builder. The returned builder is equivalent to the builder
499 * generated by {@link ImmutableMultiset#builder}.
500 */
501 public Builder() {
502 this(LinkedHashMultiset.<E>create());
503 }
504
505 Builder(Multiset<E> contents) {
506 this.contents = contents;
507 }
508
509 /**
510 * Adds {@code element} to the {@code ImmutableMultiset}.
511 *
512 * @param element the element to add
513 * @return this {@code Builder} object
514 * @throws NullPointerException if {@code element} is null
515 */
516
517 @Override
518 public Builder<E> add(E element) {
519 contents.add(checkNotNull(element));
520 return this;
521 }
522
523 /**
524 * Adds a number of occurrences of an element to this {@code
525 * ImmutableMultiset}.
526 *
527 * @param element the element to add
528 * @param occurrences the number of occurrences of the element to add. May
529 * be zero, in which case no change will be made.
530 * @return this {@code Builder} object
531 * @throws NullPointerException if {@code element} is null
532 * @throws IllegalArgumentException if {@code occurrences} is negative, or
533 * if this operation would result in more than {@link Integer#MAX_VALUE}
534 * occurrences of the element
535 */
536 public Builder<E> addCopies(E element, int occurrences) {
537 contents.add(checkNotNull(element), occurrences);
538 return this;
539 }
540
541 /**
542 * Adds or removes the necessary occurrences of an element such that the
543 * element attains the desired count.
544 *
545 * @param element the element to add or remove occurrences of
546 * @param count the desired count of the element in this multiset
547 * @return this {@code Builder} object
548 * @throws NullPointerException if {@code element} is null
549 * @throws IllegalArgumentException if {@code count} is negative
550 */
551 public Builder<E> setCount(E element, int count) {
552 contents.setCount(checkNotNull(element), count);
553 return this;
554 }
555
556 /**
557 * Adds each element of {@code elements} to the {@code ImmutableMultiset}.
558 *
559 * @param elements the elements to add
560 * @return this {@code Builder} object
561 * @throws NullPointerException if {@code elements} is null or contains a
562 * null element
563 */
564
565 @Override
566 public Builder<E> add(E... elements) {
567 super.add(elements);
568 return this;
569 }
570
571 /**
572 * Adds each element of {@code elements} to the {@code ImmutableMultiset}.
573 *
574 * @param elements the {@code Iterable} to add to the {@code
575 * ImmutableMultiset}
576 * @return this {@code Builder} object
577 * @throws NullPointerException if {@code elements} is null or contains a
578 * null element
579 */
580
581 @Override
582 public Builder<E> addAll(Iterable<? extends E> elements) {
583 if (elements instanceof Multiset) {
584 Multiset<? extends E> multiset = Multisets.cast(elements);
585 for (Entry<? extends E> entry : multiset.entrySet()) {
586 addCopies(entry.getElement(), entry.getCount());
587 }
588 } else {
589 super.addAll(elements);
590 }
591 return this;
592 }
593
594 /**
595 * Adds each element of {@code elements} to the {@code ImmutableMultiset}.
596 *
597 * @param elements the elements to add to the {@code ImmutableMultiset}
598 * @return this {@code Builder} object
599 * @throws NullPointerException if {@code elements} is null or contains a
600 * null element
601 */
602
603 @Override
604 public Builder<E> addAll(Iterator<? extends E> elements) {
605 super.addAll(elements);
606 return this;
607 }
608
609 /**
610 * Returns a newly-created {@code ImmutableMultiset} based on the contents
611 * of the {@code Builder}.
612 */
613
614 @Override
615 public ImmutableMultiset<E> build() {
616 return copyOf(contents);
617 }
618 }
619 }