在Java中对数组列表进行排序 [英] Sorting array list in Java

查看:309
本文介绍了在Java中对数组列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下课。在这里,Iris是另一个具有某些属性的类。

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;
    }
}

我想对这个数组列表进行排序(即List< Helper> helperList),基于距离参数降序。我写了以下方法,但它没有工作。

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?

推荐答案

你为什么不拿到你的助手实现 Comparable 接口的类,然后使用Collections类提供的内置排序方法。

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) 

我认为这样可以解决问题。另外,这个 sort 方法是稳定的。

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

http://docs.oracle.com/javase/7/docs/api /java/util/Collections.html#sort%28java.util.List%29

http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

实现Comparable接口:

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));

    }
}

这篇关于在Java中对数组列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆