RegularImmutableMultiset.java revision 1d580d0f6ee4f21eb309ba7b509d2c6d671c4044
1/*
2 * Copyright (C) 2011 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.Iterator;
22import java.util.Map;
23
24import javax.annotation.Nullable;
25
26/**
27 * Implementation of {@link ImmutableMultiset} with one or more elements.
28 *
29 * @author Jared Levy
30 * @author Louis Wasserman
31 */
32@GwtCompatible(serializable = true)
33@SuppressWarnings("serial")
34// uses writeReplace(), not default serialization
35class RegularImmutableMultiset<E> extends ImmutableMultiset<E> {
36  private final transient ImmutableMap<E, Integer> map;
37  private final transient int size;
38
39  RegularImmutableMultiset(ImmutableMap<E, Integer> map, int size) {
40    this.map = map;
41    this.size = size;
42  }
43
44  @Override
45  boolean isPartialView() {
46    return map.isPartialView();
47  }
48
49  @Override
50  public int count(@Nullable Object element) {
51    Integer value = map.get(element);
52    return (value == null) ? 0 : value;
53  }
54
55  @Override
56  public int size() {
57    return size;
58  }
59
60  @Override
61  public boolean contains(@Nullable Object element) {
62    return map.containsKey(element);
63  }
64
65  @Override
66  public ImmutableSet<E> elementSet() {
67    return map.keySet();
68  }
69
70  @Override
71  UnmodifiableIterator<Entry<E>> entryIterator() {
72    final Iterator<Map.Entry<E, Integer>> mapIterator =
73        map.entrySet().iterator();
74    return new UnmodifiableIterator<Entry<E>>() {
75      @Override
76      public boolean hasNext() {
77        return mapIterator.hasNext();
78      }
79
80      @Override
81      public Entry<E> next() {
82        Map.Entry<E, Integer> mapEntry = mapIterator.next();
83        return Multisets.immutableEntry(mapEntry.getKey(), mapEntry.getValue());
84      }
85    };
86  }
87
88  @Override
89  public int hashCode() {
90    return map.hashCode();
91  }
92
93  @Override
94  int distinctElements() {
95    return map.size();
96  }
97}
98