1/* 2 * Copyright (C) 2007 The Guava Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.google.common.collect; 18 19import com.google.common.annotations.GwtCompatible; 20 21import java.util.LinkedHashMap; 22 23/** 24 * A {@code Multiset} implementation with predictable iteration order. Its 25 * iterator orders elements according to when the first occurrence of the 26 * element was added. When the multiset contains multiple instances of an 27 * element, those instances are consecutive in the iteration order. If all 28 * occurrences of an element are removed, after which that element is added to 29 * the multiset, the element will appear at the end of the iteration. 30 * 31 * @author Kevin Bourrillion 32 * @author Jared Levy 33 * @since 2.0 (imported from Google Collections Library) 34 */ 35@GwtCompatible(serializable = true, emulated = true) 36@SuppressWarnings("serial") // we're overriding default serialization 37public final class LinkedHashMultiset<E> extends AbstractMapBasedMultiset<E> { 38 39 /** 40 * Creates a new, empty {@code LinkedHashMultiset} using the default initial 41 * capacity. 42 */ 43 public static <E> LinkedHashMultiset<E> create() { 44 return new LinkedHashMultiset<E>(); 45 } 46 47 /** 48 * Creates a new, empty {@code LinkedHashMultiset} with the specified expected 49 * number of distinct elements. 50 * 51 * @param distinctElements the expected number of distinct elements 52 * @throws IllegalArgumentException if {@code distinctElements} is negative 53 */ 54 public static <E> LinkedHashMultiset<E> create(int distinctElements) { 55 return new LinkedHashMultiset<E>(distinctElements); 56 } 57 58 /** 59 * Creates a new {@code LinkedHashMultiset} containing the specified elements. 60 * 61 * <p>This implementation is highly efficient when {@code elements} is itself 62 * a {@link Multiset}. 63 * 64 * @param elements the elements that the multiset should contain 65 */ 66 public static <E> LinkedHashMultiset<E> create( 67 Iterable<? extends E> elements) { 68 LinkedHashMultiset<E> multiset = 69 create(Multisets.inferDistinctElements(elements)); 70 Iterables.addAll(multiset, elements); 71 return multiset; 72 } 73 74 private LinkedHashMultiset() { 75 super(new LinkedHashMap<E, Count>()); 76 } 77 78 private LinkedHashMultiset(int distinctElements) { 79 // Could use newLinkedHashMapWithExpectedSize() if it existed 80 super(new LinkedHashMap<E, Count>(Maps.capacity(distinctElements))); 81 } 82} 83 84