1

I am trying to sort an ordered list with objects, but I am not sure how to do it. I am putting in objects with a population(integer) associated with it. How would I make a method to sort the list so that the object with the lowest population would be first, and the object with the highest population would be last.

tb14-
  • 29
  • 1

1 Answers1

1

"For any class to support natural ordering, it should implement the Comparable interface and override it’s compareTo() method. It must return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object."

public class YourObject implements Comparable<YourObject> {

  int population;

  YourObject(int pop) {
    population = pop;
  }

  @Override
  public int compareTo(YourObject other) 
  {
      return this.population - other.population;
  }
}

then you can use Collections.sort(list) on your list

  • 1
    Don't use subtraction to sort by `int` values. Use [`Integer.compare(int x, int y)`](https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#compare-int-int-). – Andreas Apr 05 '20 at 20:19