Multiset

Report a typo

Wow! This problem is kind of tricky. If you're ready to put your thinking cap on, brace yourself and good luck! Otherwise, you can skip it for now and return any time later

To deal with various tasks you may need collections which are not included in standard Java libraries. In this case, let’s create a collection that represents the concept of multiset, which is a generalization of a set.

Multiset is a collection that supports order-independent equality. As with sets, the order of the elements in a multiset does not matter. Unlike sets, multiset can store duplicate elements. The number of instances of an element is called multiplicity.

For example, let’s consider the following multiset:

{a, a, b, b, b, c}

The multiplicity of a is 2, the multiplicity of b is 3, the multiplicity of c is 1. If a multiset does not have an element, the multiplicity of it is 0.

In this task, you should implement all methods of the generic class HashMultiset according to its interface. This class is based on the HashMap class. The description of the methods is provided in the interface. It will help you to understand the common Multiset operations (add, remove, union, intersection and so on). Feel free to use additional methods if it is necessary for your solution.

Tip: If you have difficulties with union and intersection operations, look at the examples below:

Union

Initial multisets:

{1, 2, 2, 2, 4}

{2, 2, 4, 5, 6}

Result:

{1, 2, 2, 2, 4, 5, 6}


Intersection

Initial multisets:

{1, 2, 2, 2, 4}

{2, 2, 4, 5, 6}

Result:

{2, 2, 4}

Write a program in Java 17
import java.util.*;

interface Multiset<E> {

/**
* Add an element to the multiset.
* It increases the multiplicity of the element by 1.
*/
void add(E elem);

/**
* Remove an element from the multiset.
* It decreases the multiplicity of the element by 1.
*/
void remove(E elem);

/**
* Unite this multiset with another one. The result is the modified multiset (this).
* It will contain all elements that are present in at least one of the initial multisets.
* The multiplicity of each element is equal to the maximum multiplicity of
* the corresponding elements in both multisets.
*/
void union(Multiset<E> other);

/**
* Intersect this multiset with another one. The result is the modified multiset (this).
* It will contain all elements that are present in the both multisets.
* The multiplicity of each element is equal to the minimum multiplicity of
* the corresponding elements in the intersecting multisets.
*/
void intersect(Multiset<E> other);

/**
* Returns multiplicity of the given element.
* If the set doesn't contain it, the multiplicity is 0
*/
___

Create a free account to access the full topic