Search code examples
javacollectionscomparable

Integer in compareTo()


Is it possible to compare Integers in the compareTo() method in conjunction with Collections.sort() because when I run the following code it will not compile; the compiler says there is an error with this as it compares this to the other integer.I am trying to sort the numbers in descending order.

import java.util.*;

public class main implements Comparable <Integer> {
  public static void main(String [] args) {
    ArrayList <Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(2);
    list.add(5);
    list.add(4);
    Collections.sort(list);
    System.out.println(list);
  }


  public int compareTo(Integer other) {
    if (this > other){
      return -1;
    }

    if (this < other){
      return 1;
    }

    return 0;
  }
}

Solution

  • this is an instance of main, you can't apply the < or > operators to it. And frankly, you don't need to. Just use Integer's natural ordering and revere it:

    list.sort(Comparator.<Integer>naturalOrder().reversed());