简体   繁体   中英

How to implement a templated class that implements Collections

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...

The only collections that implement ordering are SortedMap and SortedSet , and neither of those puts a bound on the type parameter. Internally I suppose it casts to Comparable<E> and throws the ClassCastExcepton if that fails. The unordered collections depend only on equals() and hashCode() , and do not need a 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.

  1. If E overrides the equals() and hashCode() methods properly, E itself will be able to determine if the element is within this collection.
  2. If it has not overrode the 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() .

You can bound the type E

public class Storage<E  **extends Comparable**> implements java.util.Collection<E>

And you can parameterize the Comparable as you need to as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM