如何在Java中按从小到大的顺序对有序列表中的数字进行排序?

huangapple go评论70阅读模式
英文:

How to sort ordered lists based on numbers from smallest to biggest in java?

问题

我正在尝试对一个包含对象的有序列表进行排序,但我不太清楚该如何操作。我在列表中放置了带有人口(整数)的对象。我该如何创建一个方法来对列表进行排序,以使得人口最低的对象排在第一位,而人口最高的对象排在最后。

英文:

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.

答案1

得分: 1

"要使任何类支持自然排序,它应该实现Comparable接口并重写其compareTo()方法。它必须返回一个负整数、零或正整数,以使该对象小于、等于或大于指定的对象。"

public class YourObject implements Comparable<YourObject> {

  int population;

  YourObject(int pop) {
    population = pop;
  }

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

然后你可以在列表上使用Collections.sort(list)

英文:

"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&lt;YourObject&gt; {

  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

huangapple
  • 本文由 发表于 2020年4月6日 04:04:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/61048748.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定