Reputation: 3303
I am building a generic binary tree class in Java. I have not worked with generics too much before, so I do not know if I am doing this properly. Here is some code followed by my question:
public class Node<T> {
T data;
Node<T> left, right;
//assume setters and getters
}
public class BinaryTree<T extends Comparable <T>> {
private Node<T> root;
//assume typical setter/getter and insert, delete, etc methods
public void inOrderTraversal() {
//create instance of the inorder class here and call its traverse() method.
}
}
//define a family of algorithms for preorder, inorder and postorder traversals
public interface BinaryTreeTraversal {
public void traverse();
}
//of course there will be a class for each type of traversal...
//in order, pre order, post order
class PreOrderTraversal extends BinaryTree implements BinaryTreeTraversal {
public void traverse() { traverse(super.getRoot() ); }
private void traverse(Node<T>) {
//the three lines of code this takes
}
}
So the problem I am having is that I keep getting errors saying missing type T, or unknown type T. So I tried changing the class heading it to
class PreOrderTraversal extends BinaryTree<T> implements BinaryTreeTraversal { }
and
class PreOrderTraversal extends BinaryTree<T extends Comparable<T>> implements BinaryTreeTraversal { }
and it did not work due to similar errors. What is a way that I can make this work? I am trying to apply a strategy pattern to the traversals. I just want to be able to have three types of traversals for any generic type. Any tips would be appreciated. Thank you.
Upvotes: 0
Views: 81
Reputation: 5239
private class PreOrderTraversal< T extends Comparable< T > > extends BinaryTree< T > implements BinaryTreeTraversal { ... }
For generic classes, the parameter and all its constraints go right next to the name of the class being defined. Unfortunately, that syntax was not chosen for generic methods, where the generic type parameters and constraints precede the return type.
Upvotes: 1
Reputation: 2914
your class PreOrderTraversal
implements you generic class BinaryTree
so here you need to define the type of T like
java
class PreOrderTraversal extends BinaryTree<Integer> implements BinaryTreeTraversal {
private void traverse(Node<Integer>) {
}
}
where Integer
would by the type you are storing in the binary tree, now
Upvotes: 0