Results 1 to 4 of 4
- 10-29-2008, 09:01 PM #1
Member
- Join Date
- Oct 2008
- Posts
- 10
- Rep Power
- 0
Can generic types implement an interface?
Is there any way to do make a generic type declaration such that the type implements some interface?
For example, suppose I want to write a method that sorts anything that implements comparable (further, suppose for academic reasons that I do not want to use Collections.Sort). Then I want a generic type T such that T implements Comparable. Yet I believe the following code is invalid java:
How can I work around this?Java Code:public static <T implements Comparable> T sort(Collection<T> coll){ ...sorting algorithm goes here... }
- 10-29-2008, 09:25 PM #2
I'm no expert in Generics, but I believe that should be
orJava Code:<T extends Comparable>
dbJava Code:<T extends Comparable<T>>
- 10-29-2008, 10:39 PM #3
Senior Member
- Join Date
- Sep 2008
- Posts
- 564
- Rep Power
- 5
I didn't know the answer either, but a quick Google search (Francisoud's Blog: Java generics and interface) supports what Darryl.Burke says.
- 10-30-2008, 04:07 AM #4
Member
- Join Date
- Oct 2008
- Posts
- 10
- Rep Power
- 0
Burke is right I need to extend Comparable. What I want is a method that works over all types T such that T is comparable, to return a collection of type T. The correct type signature of the method is
Then the next step is not to figure out how to sort it, that is just a sorting algorithm. The question is, does this method actually make sense. Does it make sense to sort any collection?Java Code:public static <T extends Comparable<T>> Collection<T> sort(Collection<T> coll){ return coll; }
No, of course not. Lists should be sorted, and arrays, and arrayLists, and maybe some others, vector? But Tree, Set, Map, Bag? I can't find any reason to sort these. So, instead of a method that sorts a collection of Type<T> and returns a collection of type<T>, perhaps it is more appropriate to identify some collection interface, where every implementor is sortable, and go from there. I don't really know my way around collections. Any suggestions?
Similar Threads
-
Requesting some tips to implement an interface between a tree structure and table
By Karanam in forum AWT / SwingReplies: 1Last Post: 10-20-2008, 12:58 PM -
How to implement the Icon interface in Java
By Java Tip in forum java.awtReplies: 0Last Post: 06-23-2008, 11:17 PM -
A generic interface example
By Java Tip in forum java.langReplies: 0Last Post: 04-17-2008, 07:42 PM -
Generic array
By eva in forum New To JavaReplies: 3Last Post: 12-23-2007, 12:12 AM -
Generic Hashtables
By ShoeNinja in forum New To JavaReplies: 0Last Post: 12-04-2007, 10:43 PM


LinkBack URL
About LinkBacks

Bookmarks