File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes generics (error in return type) Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "generics (error in return type)" Watch "generics (error in return type)" New topic
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: generics (error in return type)
 
Similar Threads
compiler inferencing in generic methods
Doubt in generic method
Generics Warnings
Trouble with a toy tree [SOLVED]
Simple J2SE 5.0 Tiger Notes