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.collections.bag;
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 import org.apache.commons.collections.Bag;
27
28 /**
29 * Implements {@link Bag}, using a {@link HashMap} to provide the
30 * data storage. This is the standard implementation of a bag.
31 * <p>
32 * A {@link Bag} stores each object in the collection together with a
33 * count of occurrences. Extra methods on the interface allow multiple copies
34 * of an object to be added or removed at once. It is important to read the
35 * interface javadoc carefully as several methods violate the
36 * {@link Collection} interface specification.
37 *
38 * @since 3.0 (previously in main package v2.0)
39 * @version $Id: HashBag.java 1429905 2013-01-07 17:15:14Z ggregory $
40 */
41 public class HashBag<E> extends AbstractMapBag<E> implements Bag<E>, Serializable {
42
43 /** Serial version lock */
44 private static final long serialVersionUID = -6561115435802554013L;
45
46 /**
47 * Constructs an empty {@link HashBag}.
48 */
49 public HashBag() {
50 super(new HashMap<E, MutableInteger>());
51 }
52
53 /**
54 * Constructs a bag containing all the members of the given collection.
55 *
56 * @param coll a collection to copy into this bag
57 */
58 public HashBag(final Collection<? extends E> coll) {
59 this();
60 addAll(coll);
61 }
62
63 //-----------------------------------------------------------------------
64 /**
65 * Write the bag out using a custom routine.
66 */
67 private void writeObject(final ObjectOutputStream out) throws IOException {
68 out.defaultWriteObject();
69 super.doWriteObject(out);
70 }
71
72 /**
73 * Read the bag in using a custom routine.
74 */
75 private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
76 in.defaultReadObject();
77 super.doReadObject(new HashMap<E, MutableInteger>(), in);
78 }
79
80 }