Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Generic Comparator for Generic Type

dadams07Jan 19 2010 — edited Jan 19 2010
I'm trying to write a generic Comparator for my generic type Pair, which is defined as follows:
public class Pair<F extends Object, S extends Object> {

private final F first; 
private final S second; 


public F getFirst() {
return first;
}
public S getSecond() {
return second;
}
...
}
I'd like a generic comparator which can accept (for example) two Pair<String,String> objects, or perhaps two Pair<Character,String> objects, etc. My first stab at it:
public static final Comparator<Pair<Comparable,Comparable>> PAIR_COMPARATOR =new Comparator<Pair<Comparable,Comparable>>() { 


public int compare(final Pair<Comparable,Comparable> p1, final Pair<Comparable,Comparable> p2) { 


int result = _p1.getFirst().compareTo(p2.getFirst())_; 


if (result == 0) { 


result = _p1.getSecond().compareTo(p2.getSecond())_; 


} 


return result; 


} 


}; 
The compiler complains thusly: "Type safety: The method compareTo(Object) belongs to the raw type Comparable. References to generic type Comparable<T> should be parameterized." Any ideas on how to make this work would be greatly appreciated!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 16 2010
Added on Jan 19 2010
10 comments
1,801 views