DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 3 of 3
  1. #1
    Join Date
    Apr 2009

    Unhappy 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....

  2. #2
    Join Date
    Dec 2004
    San Bernardino County, California
    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:

    Last edited by nspils; 04-09-2009 at 09:27 PM.

  3. #3
    Join Date
    Mar 2007
    Bangalore, India
    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.

    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

  1. Compare and removing elements
    By andy38 in forum .NET
    Replies: 3
    Last Post: 02-12-2009, 06:41 PM
  2. Replies: 2
    Last Post: 12-27-2005, 01:39 AM
  3. Comparing XML's
    By Alex Kennedy in forum XML
    Replies: 1
    Last Post: 03-07-2003, 05:20 AM
  4. xml attributes vs. elements
    By monife in forum XML
    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
HTML5 Development Center
Latest Articles
Questions? Contact us.
Web Development
Latest Tips
Open Source

   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center

We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.