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 com.google.common.annotations.GwtCompatible;
020import com.google.common.annotations.GwtIncompatible;
021
022/**
023 * Multiset implementation that uses hashing for key and entry access.
024 *
025 * @author Kevin Bourrillion
026 * @author Jared Levy
027 * @since 2.0
028 */
029@GwtCompatible(serializable = true, emulated = true)
030public class HashMultiset<E> extends AbstractMapBasedMultiset<E> {
031
032  /** Creates a new, empty {@code HashMultiset} using the default initial capacity. */
033  public static <E> HashMultiset<E> create() {
034    return create(ObjectCountHashMap.DEFAULT_SIZE);
035  }
036
037  /**
038   * Creates a new, empty {@code HashMultiset} with the specified expected number of distinct
039   * elements.
040   *
041   * @param distinctElements the expected number of distinct elements
042   * @throws IllegalArgumentException if {@code distinctElements} is negative
043   */
044  public static <E> HashMultiset<E> create(int distinctElements) {
045    return new HashMultiset<E>(distinctElements);
046  }
047
048  /**
049   * Creates a new {@code HashMultiset} containing the specified elements.
050   *
051   * <p>This implementation is highly efficient when {@code elements} is itself a {@link Multiset}.
052   *
053   * @param elements the elements that the multiset should contain
054   */
055  public static <E> HashMultiset<E> create(Iterable<? extends E> elements) {
056    HashMultiset<E> multiset = create(Multisets.inferDistinctElements(elements));
057    Iterables.addAll(multiset, elements);
058    return multiset;
059  }
060
061  HashMultiset(int distinctElements) {
062    super(distinctElements);
063  }
064
065  @Override
066  void init(int distinctElements) {
067    backingMap = new ObjectCountHashMap<>(distinctElements);
068  }
069
070  @GwtIncompatible // Not needed in emulated source.
071  private static final long serialVersionUID = 0;
072}