S
Steven Davies
Hi,
I'm having my first go at wrestling with parameterised types in Java and
I've come across something which I can't quite get my head around, or at
least I don't know how I could implement it:
I need to write a binary tree class which can store a lot of the same
item (hence the generics), which all implement the Comparable interface
to make it easier to insert them into the tree.
I don't have a problem with writing the actual insert/find/remove
algorithms, but I can't work out how to define a BinaryTree class that
can only take Comparable elements of a certain class - something like:
public class BinaryTree<E implements Comparable> {}
...and then have a TreeNode class which takes the same object type as the
BinaryTree and stores a reference to that particular object and pointers
to the parent/left/right nodes in the tree.
I know I could implement it by creating a BinaryTree of Comparables, but
then someone could accidentally insert a different element into the
tree, causing ClassCastExceptions all over the place. Another
alternative would be to hard-code the classes to the one I'm using for
this project, which I know includes compareTo, but that's not very
extensible..
If that makes any sense to anyone, can you describe if and how it could
be done please?
Thanks,
Steven Davies
I'm having my first go at wrestling with parameterised types in Java and
I've come across something which I can't quite get my head around, or at
least I don't know how I could implement it:
I need to write a binary tree class which can store a lot of the same
item (hence the generics), which all implement the Comparable interface
to make it easier to insert them into the tree.
I don't have a problem with writing the actual insert/find/remove
algorithms, but I can't work out how to define a BinaryTree class that
can only take Comparable elements of a certain class - something like:
public class BinaryTree<E implements Comparable> {}
...and then have a TreeNode class which takes the same object type as the
BinaryTree and stores a reference to that particular object and pointers
to the parent/left/right nodes in the tree.
I know I could implement it by creating a BinaryTree of Comparables, but
then someone could accidentally insert a different element into the
tree, causing ClassCastExceptions all over the place. Another
alternative would be to hard-code the classes to the one I'm using for
this project, which I know includes compareTo, but that's not very
extensible..
If that makes any sense to anyone, can you describe if and how it could
be done please?
Thanks,
Steven Davies