java对数组进行排序,在Java中对数组列表进行排序

博客讨论了如何根据distance参数对Helper类对象的ArrayList进行降序排序。作者提供了一个自定义排序方法,但未成功。解决方案建议实现Comparable接口,并使用Collections.sort()内置方法,该方法稳定且能按需求排序。同时,给出了Helper类实现Comparable接口的示例代码。
摘要由CSDN通过智能技术生成

I have following class. In this, Iris is another class with some attributes.

public class Helper {

Iris iris;

double distance;

public Helper(Iris iris, double distance) {

this.iris = iris;

this.distance = distance;

}

}

I want to sort an array list of this (i.e List < Helper > helperList), descending based on distance parameter. I have written the following method but it is not working.

public void sort(){

for(int k=0; k < helperList.size(); k++)

{

double distance = helperList.get(k).distance;

for(int l=0; l < helperList.size(); l++)

{

Helper temp = helperList.get(l);

if( distance < temp.distance )

{

helperList.set(l, helperList.get(k));

helperList.set(k, temp);

}

}

}

}

Can anybody suggest a solution?

解决方案

Why don't you get your Helper class to implement Comparable interface and then use the in-built sort method offered by the Collections class.

Collections.sort(helperList)

I think that would solve the problem. Plus, this sort method is stable.

Implementing Comparable interface:

public class Helper implements Comparable{

Iris iris;

double distance;

public Helper(Iris iris, double distance) {

this.iris = iris;

this.distance = distance;

}

public int compareTo(Helper other) {

return new Double(this.distance).compareTo(new Double(other.distance));

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值