1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.commons.collections4.multiset;
18
19 import java.io.IOException;
20 import java.io.ObjectInputStream;
21 import java.io.ObjectOutputStream;
22 import java.io.Serializable;
23 import java.util.Collection;
24 import java.util.HashMap;
25
26 /**
27 * Implements {@code MultiSet}, using a {@link HashMap} to provide the
28 * data storage. This is the standard implementation of a multiset.
29 * <p>
30 * A {@code MultiSet} stores each object in the collection together with a
31 * count of occurrences. Extra methods on the interface allow multiple copies
32 * of an object to be added or removed at once.
33 * </p>
34 *
35 * @param <E> the type held in the multiset
36 * @since 4.1
37 */
38 public class HashMultiSet<E> extends AbstractMapMultiSet<E> implements Serializable {
39
40 /** Serial version lock */
41 private static final long serialVersionUID = 20150610L;
42
43 /**
44 * Constructs an empty {@link HashMultiSet}.
45 */
46 public HashMultiSet() {
47 super(new HashMap<>());
48 }
49
50 /**
51 * Constructs a multiset containing all the members of the given collection.
52 *
53 * @param coll a collection to copy into this multiset
54 */
55 public HashMultiSet(final Collection<? extends E> coll) {
56 this();
57 addAll(coll);
58 }
59
60 /**
61 * Deserializes the multiset in using a custom routine.
62 *
63 * @param in the input stream
64 * @throws IOException if an error occurs while reading from the stream
65 * @throws ClassNotFoundException if an object read from the stream cannot be loaded
66 */
67 private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
68 in.defaultReadObject();
69 setMap(new HashMap<>());
70 super.doReadObject(in);
71 }
72
73 /**
74 * Serializes this object to an ObjectOutputStream.
75 *
76 * @param out the target ObjectOutputStream.
77 * @throws IOException thrown when an I/O errors occur writing to the target stream.
78 */
79 private void writeObject(final ObjectOutputStream out) throws IOException {
80 out.defaultWriteObject();
81 super.doWriteObject(out);
82 }
83
84 }