| Author |
generics (error in return type)
|
silvio relli
Greenhorn
Joined: Mar 07, 2005
Posts: 1
|
|
Hi to everyone, I'm new around there! I have 2 questions to ask: I tryed to implement a generic tree inside of wich I created a "search" method. This method needs the method "compareTo" of the class "Comparable" to compare nodes, so the tree class requires a bound and the header is the following: public class BTNodeGen <T extends Comparable> The problem is that in this whay the search method returns a Comparable instead of a generic type. The method is the following: public <T extends Comparable> T search(T el) { if (el.compareTo(key)==0) { return(el); } else if((el.compareTo(key)<0) && (left != null)) { return ((T)left.search(el)); } else if(right != null) { return ((T)right.search(el)); } else { return null; } } This method works and returns a T only because I added some downcast to T before the return, otherwise it gives a compile error because it is returned a Comparable where is expected a T. How can I do to avoid downcasts (that aren't so much correct for a OO language...)? Can you help me? A last question: what changes between the following header of the method search: - public <T extends Comparable> T search(T el) - public T search(T el) and between the following class header - public class BTNodeGen<T extends Comparable> - public class BTNodeGen<T extends Comparable<T>> Thanks for all
|
 |
 |
|
|
subject: generics (error in return type)
|
|
|