Generic programming help
-
Hi, I need to make a generic version of Binary Search Tree, I've non generic version which uses comparable as a data on the node. Therefore I need to define generic type such that it should be an sub class of Comparable interface. Note: Comparable it self is a generic type. This what I've done so far but its giving me compiler errors.
Comparable data;
void addNode(Node n)
{
//Some code
int c = data.compareTo(n.data);
}In the code above, data is of type Comparable thus it has method compareTo(E data), but when I cast ((E)n.data) it gives me error that its not type safe. But I dunno why when I've defined Comparable data, then why can't I cast data?? Any help will be appreciated.
-
Hi, I need to make a generic version of Binary Search Tree, I've non generic version which uses comparable as a data on the node. Therefore I need to define generic type such that it should be an sub class of Comparable interface. Note: Comparable it self is a generic type. This what I've done so far but its giving me compiler errors.
Comparable data;
void addNode(Node n)
{
//Some code
int c = data.compareTo(n.data);
}In the code above, data is of type Comparable thus it has method compareTo(E data), but when I cast ((E)n.data) it gives me error that its not type safe. But I dunno why when I've defined Comparable data, then why can't I cast data?? Any help will be appreciated.
note: Comparable<T> is the Java version, in C# it's IComparable<T> The problem is that data would have to be IComparable<E> and E both at the same time - that could be the case, but it is not guaranteed (you could try to feed it an invalid type, and C# generics aren't C++ templates). So you must constrain the type E to be Comparable<E> in the class definition of the Binary Search Tree (and/or Node, depending on whether it is a nested type or not)
class BST where E : IComparable
{
E data;
// etc
} -
note: Comparable<T> is the Java version, in C# it's IComparable<T> The problem is that data would have to be IComparable<E> and E both at the same time - that could be the case, but it is not guaranteed (you could try to feed it an invalid type, and C# generics aren't C++ templates). So you must constrain the type E to be Comparable<E> in the class definition of the Binary Search Tree (and/or Node, depending on whether it is a nested type or not)
class BST where E : IComparable
{
E data;
// etc
}And how do you constaring generic types in class definition for JAVA. I read on Google that you can constraint in method definition not in beginning of the class.
-
And how do you constaring generic types in class definition for JAVA. I read on Google that you can constraint in method definition not in beginning of the class.
-
NVM, I got it. In java code is this way..
class BinarySearchTree>
Where
? super T
denotes any super class of type T. Thanks for the help. :) Shivam Kalra