acourchesne acourchesne - 1 year ago 91
Java Question

Java Data structure for Set with duplicates

I want to parse words in a data structure like

java.util.HashSet
, i.e:


  • I don't need to keep them in any order (So no index)

  • I want to be able to find if the set contain a value quickly



But the
HashSet
does not allow duplicates. What data structure could I use ?

I could use
ArrayList
, but the search is slower than hash functions.
I could use
HashMap
and add an index for each character to have a Key-Value pair, but I would like to keep it as simple as possible and limit the memory used.

Answer Source

You are looking for multiset(or a bag). Multiset is similar to set but it accepts duplicates.Java library does not come with Multiset implemetation. Google's gauva library has an implementation of Multiset.

Methods on multiset

boolean add(E element): Adds a single occurrence of the specified element to this multiset.

int add(E element, int occurrences): Adds a number of occurrences of an element to this multiset.

boolean contains(Object element): Determines whether this multiset contains the specified element.

int count(Object element):Returns the number of occurrences of an element in this multiset (the count of the element).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download