我在我的java程序中使用了一个链表,元素是一个自定义类型,它有三个字段,其中一个是Integer类型。我的问题是:如何根据 Integer 字段的值对链表进行排序?
最佳答案
您可以将 Collections.sort 方法与自定义比较器结合使用。
Collections.sort(your_list, new Comparator<YoureValueType>(){
@Override
public int compare(YoureValueType o1, YoureValueType o2){
if(o1.getMagicInt() < o2.getMagicInt()){
return -1;
}
if(o1.getMagicInt() > o2.getMagicInt()){
return 1;
}
return 0;
}
});
编辑:我刚刚看到 Alexandr 在 waldheinz 回答中评论了非常大和非常小的值。我更新了我的代码以反射(reflect)他的论点。
关于java - 如何根据元素的一个字段的值对java中的链表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6369757/