0

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?
}
Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106
  • Can you clarify your question? At the moment it's really unclear what you're asking. – T.J. Crowder Dec 05 '13 at 12:38
  • 1
    possible duplicate of [java class implements comparable](http://stackoverflow.com/questions/3718383/java-class-implements-comparable) – reto Dec 05 '13 at 12:39
  • Just read the comparator documentation here: http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html – Zoltán Dec 05 '13 at 12:42
  • 1
    Just think, you might want multiple comparators, so you will need multiple implementing classes. NB Comparable vs Comparator, they are slightly different – vikingsteve Dec 05 '13 at 12:42
  • @reto Possible but not for certain. That describes Comparable and this question is about Comparator. However I got to agree with T.J. though that it is not entirely clear what the question originator wants to achieve. – DanielBarbarian Dec 05 '13 at 12:43
  • Well, you determine what constitutes "less than", "equal", and "greater than" for your class and you write the code to perform the appropriate tests. It would be different for a BankAccount and a ZooAnimal. – Hot Licks Dec 05 '13 at 12:43
  • 1
    @DanielBarbarian thanks. Relevant read: http://stackoverflow.com/questions/2266827/when-to-use-comparable-vs-comparator – reto Dec 05 '13 at 12:46

2 Answers2

2

You use the java Generics, built into the Comparator interface.

public class MyClass implements Comparator<MyClass>
christopher
  • 26,815
  • 5
  • 55
  • 89
0
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;
    }
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720