0

I had a piece of code.

  compareScanMz = new Comparator<Triplet>() {
  @Override
  public int compare(Triplet o1, Triplet o2) {

    int scan1 = o1.scanListIndex;
    int scan2 = o2.scanListIndex;
    int scanCompare = Integer.compare(scan1, scan2);

    if (scanCompare != 0) {
      return scanCompare;
    } else {
      int mz1 = o1.mz;
      int mz2 = o2.mz;
      return Integer.compare(mz1, mz2);
    }
  }
};`

In the code I am able to figure out the other statements, but am unable to get the first one. i.e:

compareScanMz = new Comparator()

What does this statement mean?

  • 1
    It is an [annonymous class](https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html), implementing the `Comparator`-interface. – Turing85 Jan 13 '18 at 12:40
  • I would recommend reading the appropriate documentation for [Java 7](https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html) and [Java 8](https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html) – MechMK1 Jan 13 '18 at 12:41
  • @DavidStockinger no love for [Java 9](https://docs.oracle.com/javase/9/docs/api/java/util/Comparator.html)? :( – Turing85 Jan 13 '18 at 12:42
  • If you could explain the concept of anonymous class, that would be helpful, and please do so in the answer section. @Turing85 – Aniket Pradhan Jan 13 '18 at 12:42
  • @AniketPradhan I linked the Oracle tutorial in my comment. And as you can see, JoeC already found a question asking the same, so an answer tot h is question is superfluous. – Turing85 Jan 13 '18 at 12:42
  • 1
    @Turing85 If OP had specified which version of Java he was using, I could have pointed him to the correct version. – MechMK1 Jan 13 '18 at 12:43
  • @DavidStockinger, currently I am using Java SE 8. Thanks for your help. :D – Aniket Pradhan Jan 13 '18 at 12:45

1 Answers1

0

You are creating new comparator for Triplets and inside it you define how to compare two of them. You need id when you want to override the default compare method on the Triplets. If by default two Triplets are comparet by name, in some cases you may want to compare them by age. And for that case you write own comparator and define new comparing rules.

Nikola Andreev
  • 624
  • 4
  • 18