If I have 2 classes that extend from this container class, one that can only alter the list container and the other that can only alter the set container. How would the isEmpty() method be able to know which container to check? This is a lab for class so I'm not allowed to change any of the code already given to me.
public class Container {
// Do not change the value of the following constants.
protected final int ORIGINAL_SIZE = 10;
protected Object[] list; // is a container that stores the element of MyList
protected Object[] set; // is a container that stores the element of MySet
protected int size; // this variable holds the actual number of elements that are stored in either of the containers (i.e. MyList or MySet).
/**
* This method returns true if the container is empty.
* @return It returns true if the container is empty, otherwise false.
*/
boolean isEmpty() {
return true;
}
}
class MyList extends Container{
public MyList () {
list= new Object[ORIGINAL_SIZE];
size = 0;
}
}
class MySet extends Container{
public MySet() {
set = new Object[ORIGINAL_SIZE];
size = 0;
}
}
CodePudding user response:
You don't need to check either container. Override the isEmpty()
method in both classes to check the size
field. As elements are added or removed to either array, increment or decrement the size
accordingly.
CodePudding user response:
You need to override the isEmpty
method on the respective sub classes, and then it's clear to which collection they refer:
class MyList extends Container {
public MyList() {
list = new Object[ORIGINAL_SIZE];
size = 0;
}
@Override
public boolean isEmpty() {
return size > 0;
}
}
Here you need to maintain the size
variable each time you modify (add to or remove from) the list.
(Same for the set implementation, just using set
instead of list
.)
The whole thing is a bit of a weird class design. The Container
base class should not have list
and set
, these should be in the respective child classes MyList
and MySet
, so that everything is defined where it's used (only).