英文:
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<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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论