This is a homework problem that I am having difficulty with. The skeleton for the class is given below:
public class Storage<E> implements java.util.Collection<E> {
private Object[] data = new Object[256];
private int nextEmptySlot = 0;
@Override
public java.util.Iterator<E> iterator() {
// returns a class that iterates over the data array
return new java.util.Iterator() {
// insert the body of the inner class here
// 3 methods: remove(), hasNext(), next()
};
}
//Override all methods required by the interface
}
Now the trouble I'm having is writing functions such as contains(Object o), because the template does not force E to be comparable. How can I treat the templated type E as comparable so that I can use equals and compateTo? I know there are ways to do it in the class declaration but the class declaration is given and does not require E to be comparable...
You should not need compareTo()
because this would give you a definition of the ordering of the elements (though it can tell you if two objects are equal). Unless order is important here, this won't be what you want anyway.
If the assumption that order is not required is correct, then all you should need to rely on is the equals(
) method of each instance within the collection.
E
overrides the equals()
and hashCode()
methods properly, E
itself will be able to determine if the element is within this collection. equals()
method, then the instance will rely on Object
's implementation of equals()
which simply compares the references (if they're both non-null).I would suggest making sure you are clear on the requirement of this assignment first. If the requirements state something more specific, you may be able to determine what equality is within your collection. If you cannot get anything more clear, I believe your only choice is to rely on E
's implementation of equals()
.