For the class Bag<T> (with extendible array, defined in \"Bag.java\"), add the f
ID: 3757792 • Letter: F
Question
For the class Bag<T> (with extendible array, defined in "Bag.java"), add the following methods:
public void trimToSize() -- If the data array has unused spaces (i.e., the bag is not full), allocate a new array just enough to hold the current items. If the bag is full, do nothing.
public Comparable removeMin() -- Removes the minimum item from the bag and returns the item. Size should be decremented as well. Note the items do implement Comparable<T> in the code given. Also since the implementation of this Bag class stores items in an array from the beginning with no 'holes', the vacated slot is filled by the last element in the current array and the last slot should be nulled-out. If the bag is empty, the method returns null.
public boolean isUnique() -- returns true if all items in this bag are unique, that is, there are no duplicates. Use equals() to test for equality between the items.
Explanation / Answer
// returns true if all items in this bag are unique, that is, there are no duplicates.
// Use equals() to test for equality between the items.
public boolean isUnique() {
if(data != null && data.length > 0) {
for(int i = 0; i < data.length-1; i++) {
//compare 1st element with 2nd-to last and 2nd element with 3rd to last and so on
for(int j = i+1; j < data.length; j++) {
if(data[i].equals(data[j]))
return false;
}
}
//comes here if no duplicates
return true;
}
return false;
}
// If the data array has unused spaces (i.e., the bag is not full),
//allocate a new array just enough to hold the current items. If the bag is full, do nothing.
public void trimToSize() {
if(data.length > size) {
Comparable[ ] temp = (T [ ] ) new Comparable[size];
for (int i = 0; i < size; i++)
temp[i] = data[i];
// reassign data to point to temp
data = temp;
}
}
// -- Removes the minimum item from the bag and returns the item. Size should be decremented as well.
public Comparable removeMin() {
if(data.length > size) {
//identify the minimum element
Comparable min = data[0];
int index = 0;
for (int i = 1; i < size; i++) {
if(data[i].compareTo(min) < 0)
min = data[i];
index = i;
}
//now remove the min from array
for(int i = index; i < size-1; i++) {
data[i] = data[i+1];
}
//last item is empty now
data[size-1] = null;
//decrease size
size--;
return min;
}
return null;
}