If a class implements comparator, how can we define the compare function?
public int compare(classname c1, classname c2) {
// c1 has to be this.how can we use it?
}
If a class implements comparator, how can we define the compare function?
public int compare(classname c1, classname c2) {
// c1 has to be this.how can we use it?
}
You use the java Generics, built into the Comparator
interface.
public class MyClass implements Comparator<MyClass>
public int compare(classname c1, classname c2) {
if (cl.something > c2.something)
return 1;
else if (c1.something == c2.something)
return 0;
else
return -1;
}
Edit: with Comparable
public class classname implements Comparable<classname>{
int something;
public int compareTo(classname c2){
if (this.something > c2.something)
return 1;
else if (this.something == c2.something)
return 0;
else
return -1;
}
}