How do you use generic interfaces in Java 1.5?
December 13, 2005 11:34 AM   Subscribe

How do you use generic interfaces in Java 1.5?

I'm trying to write a class that implements the Comparable interface in Java 1.5, and the compile errors are bewildering. In 1.4.2, you could write something like
class MyEvent implements Comparable {
    double time;

    public MyEvent(double t) {
        time  = t;
    }
    
    public int compareTo(Object o) {
        double otherTime = ((MyEvent)o).time;
        return new Double(time).compareTo(new Double(otherTime));
    }
}
But I can't seem to figure out how to do this in Java 1.5. How do you write a class that is Comparable to itself? In case its relevent, I ask because I'd like to store instances of something like the above in a PriorityQueue. Thanks!
posted by gsteff to Computers & Internet (5 answers total)
 
well all i do is stick <classname> after "implements Comparable" and then write a compareTo method that takes an instance of the appropriate class.
posted by andrew cooke at 11:57 AM on December 13, 2005


This should be what you're looking for...


import java.util.PriorityQueue;
import java.util.Queue;

public class App {

class MyEvent implements Comparable<MyEvent> {

public int compareTo(MyEvent arg0) {
// TODO Auto-generated method stub
return 0;
}
}

/**
* @param args
*/
public static void main(String[] args) {
Queue<MyEvent> q = new PriorityQueue<MyEvent>();
}

}


posted by Loser at 11:58 AM on December 13, 2005


so:

class MyEvent implements Comparable<MyEvent> {
public int compareTo(MyEvent other) {...};
}
posted by andrew cooke at 11:58 AM on December 13, 2005


That should do:
class myEvent implement Comparable{
double time;



public MyEvent(double t) {

time = t;

}


public int compareTo(MyEvent otherevt) {

double otherTime = otherevt.time;

return new Double(time).compareTo(new Double(otherTime));

}

}

You can couple it with:
public class MyEventComparator implements Comparator{

public int compare(MyEvent e1, MyEvent e2) {
return e1.compareTo(e2);
}

}

Then, supposing "events" is a MyEvents ArrayList:
Collections.sort(events, new MyEventComparator());
will sort events.

posted by nkyad at 12:00 PM on December 13, 2005


Response by poster: Thanks! Problem solved.
posted by gsteff at 3:31 PM on December 13, 2005


« Older I’m in a relationship and I think we have...   |   Regular expression question Newer »
This thread is closed to new comments.