Create a class Bag (multiset) that uses an array to store the bag items. The cla
ID: 3546045 • Letter: C
Question
Create a class Bag (multiset) that uses an array to store the bag items. The class should have the methods listed below. Create a main class to test your Bag class. This main class should fill a bag of integers with 10 random numbers, each in the interval [0, 15], and print how many times each integer in the interval [0, 15] appears in the bag.
a. Bag(): default constructor that sets the size of the bag to 20
b. Bag(int size): nondefault constructor that sets the size of the bag to the value passed in size
c. boolean isEmpty(): determines whether the bag is empty
d. void display(): prints the bag elements
e. int getLength(): returns the number of items in the bag
f. int getSize(): returns the size of the bag
g. void clear(): removes all of the items from the bag
h. void add(int item): adds an item to the bag
i. void remove(int item): removes an item from the bag; all occurrences of item in the bag should be removed.
j. int count(int item): counts the number of occurrences of item in the bag
Explanation / Answer
// Bag.java
public class Bag
{
private int[] data;
private int length;
// default constructor that sets the size of the bag to 20
public Bag()
{
data = new int[20];
}
//nondefault constructor that sets the size of the bag to the value passed in size
public Bag(int size)
{
data = new int[size];
}
// determines whether the bag is empty
public boolean isEmpty()
{
return length == 0;
}
// prints the bag elements
public void display()
{
for (int i = 0; i < length; i++)
System.out.print(data[i] + " ");
System.out.println();
}
// returns the number of items in the bag
public int getLength()
{
return length;
}
// returns the size of the bag
public int getSize()
{
return data.length;
}
// removes all of the items from the bag
public void clear()
{
length = 0;
}
// adds an item to the bag
public void add(int item)
{
if (length < data.length)
{
data[length] = item;
length++;
}
}
// removes an item(all occurrences) from the bag
public void remove(int item)
{
for (int i = length - 1; i >= 0; i--)
{
if (data[i] != item)
continue;
for (int j = i+1; j < length; j++)
data[j-1] = data[j];
length--;
}
}
// counts the number of occurrences of item in the bag
public int count(int item)
{
int num = 0;
for (int i = 0; i < length; i++)
if (data[i] == item)
num++;
return num;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.