Question

In addition to implementing a Bag & List for an assignment, the next step is to create an ordered version. A requirement is to specify the parametric interface OrderedCollection with the correct type parameters and constraints. My problem is with implementing it.

An interface Collection <E> exists and is defined as

public interface Collection<E> extends Iterable<E>{
  public void add(E e);
  public void remove(E e);
  public boolean contains(Object e);
  public void clear();
  public int size();
  public boolean isEmpty();
  public Object[] toArray();
}

It is implemented by the classes

public class UnorderedList<E> implements Collection<E>
public class UnorderedBag<E> extends UnorderedList<E> implements Collection<E>

I have the structures working, and am now trying to implement the sorted version. To do this and satisfy part of the requirements, I created OrderedCollection as

public interface OrderedCollection <E extends Comparable<E>> {
  public int compareTo(E e);
}

because it is extending the methods already defined in Collection, and the only new functionality required is a compareTo() method.

However, when I try to implement OrderedList by the declaration

public class OrderedList<E> extends UnorderedList<E> implements OrderedCollection<E>

I get an error stating that

Bound mismatch: The type E is not a valid substitute for the bounded parameter <E
extends Comparable<E>> of the type OrderedCollection<E>

As I understand the error message, I need to specify a parameter type that is a valid substitute for the one given in the interface declaration. However, I've tried

OrderedCollection<E extends Comparable<E>>

as the implements declarer, but then I get a warning that a syntax error exists on extends.

How do I satisfy the requirements here?

Was it helpful?

Solution

In your declaration of the OrderedList class, the generic type of OrderedList needs to match the restriction that OrderedCollection expects.

public class OrderedList<E extends Comparable<E>> 
             extends UnorderedList<E> 
             implements OrderedCollection<E>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top