-
Comparing generic elements
Hey guys, I could really use some help, this may seem obvious, but I'm new to Java and this is driving me crazy. I'm writing a generic linked list class with a sort method. The problem I'm running into is comparing the data in the list to sort. How do I compare to generic variables, without knowing which type they are? I can't use normal operators ( I just get 'Operator > cannot be used with E,E'). If I use compareTo(), I'll have to override it and that leaves me writing a method and trying to compare E and E again. I assumed that the most difficult portion of this would be moving the iterator, but I am stuck trying to do the most basic part. Is there something obvious I'm missing? The only examples I can find simply cast the variables to integers, but this seems useless if your input is strings, or vice versa. A nudge in the right direction would be appreciated....
-
You must design your class to be Comparable (implement the Comparable interface). The list will call the elements' compareTo method to do the comparison and set the order.
Take a look at the Java Tutorial:
http://java.sun.com/docs/books/tutor...ces/order.html
Last edited by nspils; 04-09-2009 at 09:27 PM.
-
As nspils pointed, only the person who writes specific objects would know how to compare them. The implementor of the List would have no idea how to compare them. Because yours is a special list that implements sorting, you should only expect objects that are Comparable (implements Comparable interface).
More specifically, you have to restrict E to be of type Comparable only.
Code:
class CList<E extends Comparable> {
// ---- Code here ----
}
That way, within CList, you can use the compareTo method defined in Comparable within your class (CList here), without casting E.
Similar Threads
-
Replies: 3
Last Post: 02-12-2009, 06:41 PM
-
Replies: 2
Last Post: 12-27-2005, 01:39 AM
-
By Alex Kennedy in forum XML
Replies: 1
Last Post: 03-07-2003, 05:20 AM
-
Replies: 1
Last Post: 01-30-2001, 12:47 PM
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks