Question

I am having some problems with the basic setup of my class.

The background: I am writing a class which implements a MinHeap based on a binary tree. I have a class BinaryTree, BinaryTreeNode, MinTreeHeap, DefaultComparator and an interface PriorityQueue.
MinTreeHeap is the class I am writing. It implements PriorityQueue and does some other things.
DefaultComparator implements functionality to compare two nodes.

A given test program calls MinTreeHeap with the following:

MinTreeHeap<Value> heap = new MinTreeHeap<>( new DefaultComparator<Value>() );

My problem is the class declaration of MinTreeHeap. I have the following so far.

import pa01.bintree.BinaryTree;
import pa01.bintree.BinaryTreeNode;
import java.util.Comparator;
import java.util.HashMap;
import java.util.NoSuchElementException;

public class MinTreeHeap<T extends DefaultComparator<T>> extends BinaryTree 
    implements PriorityQueue<T> {

  /** The actual heap. */
  private final BinaryTree<T> heap;

  /**
   * Default Constructor
   */
  public MinTreeHeap() {
    super();
    last = null;
  }

  public MinTreeHeap( T data ){
    super(data);
    last = heap.getRoot();
  }

I am getting errors in line public class MinTree... error:

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

and I have no idea how I'm getting the functionality of my DefaultComparator into the class.

If you need further information to clarify just ask.

Thanks in advance.

Was it helpful?

Solution

You are confusing the type of the data your MinTreeHeap ought to store with the type of the comparator:

public class MinTreeHeap<T extends DefaultComparator<T>> extends BinaryTree
//                       ↑                           ↑
//                       |                            the type to compare
//                       A type extending the Comparator

Saying that T shall be both, a Comparator and the type of the items the Comparator should compare, makes no sense.

And, the DefaultComparator expects a type extending Comparable which your T type variable does not fulfill.

What you most probably meant is something like this:

public class MinTreeHeap<E, C extends Comparator<E>> extends BinaryTree 
implements PriorityQueue<E> {

where E is the type of the items to store and C the type of the Comparator (without forcing it to be a DefaultComparator.

It is also possible to go without a type variable for the type of the Comparator:

public class MinTreeHeap<E> extends BinaryTree implements PriorityQueue<E> {

public MinTreeHeap(Comparator<? super E> comp) {
  // store comp in a field of type Comparator<? super E>
  // or pass it over to other implementation code
  …
}
…
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top