按照对象/类内特定成员变量对数组进行排序

4
假设我有一个类,看起来像这样(省略了获取/设置函数):
class InfoClass{

   String name;
   String place;
   double distance;

}

我在我的主活动中创建了一个类数组,如下所示:

InfoClass[3] myInfoClass;

myInfoClass[0].name = "venue one";
myInfoClass[0].place = "place one";
myInfoClass[0].distance = 11.23234;

myInfoClass[1].name = "venue two";
myInfoClass[1].place = "place two";
myInfoClass[1].distance = 9.2345643;

myInfoClass[2].name = "venue three";
myInfoClass[2].place = "place three";
myInfoClass[2].distance = 5.23432;

我该如何对我的数组(myInfoClass[])按照distance成员进行排序? 例如在上面的例子中,数组会被颠倒,因为元素[2]具有最小的distance而元素[0]具有最大的distance?

是否有一些函数可以添加到我的类中来完成此操作或者其他方法可行?

8个回答

5
这应该可以运行...
    public static void main(String[] args){
    InfoClass[] dd = new InfoClass[3];

    Arrays.sort(dd, new Comparator<InfoClass>(){

        @Override
        public int compare(InfoClass arg0, InfoClass arg1) {
            // TODO Auto-generated method stub
            if(arg0.distance == arg1.distance){
                return 0;
            }else if(arg0.distance < arg1.distance){
                return -1;
            }else{
                return 1;
            }
        }
    });
}

4

使用 java.util.Arrays.sort() 并指定自己的 Comparator

InfoClass[] myInfoClass = new InfoClass[3];

myInfoClass[0] = new InfoClass();
myInfoClass[1] = new InfoClass();
myInfoClass[2] = new InfoClass();

myInfoClass[0].name = "venue one";
myInfoClass[0].place = "place one";
myInfoClass[0].distance = 11.23234;

myInfoClass[1].name = "venue two";
myInfoClass[1].place = "place two";
myInfoClass[1].distance = 9.2345643;

myInfoClass[2].name = "venue three";
myInfoClass[2].place = "place three";
myInfoClass[2].distance = 5.23432;

Arrays.sort(myInfoClass,
            new Comparator<InfoClass>()
            {
                public int compare(InfoClass o1, InfoClass o2)
                {
                    if (o1.distance == o2.distance)
                    {
                        return 0;
                    }
                    else if (o1.distance < o2.distance)
                    {
                        return -1;
                    }
                    return 1;
                }
            });

谢谢您的回复,不过我使用了上面的答案,因为它允许我像帖子中建议的那样将函数封装在类内部,感谢您的回复,我相信这个答案也是可行的。+1 - brux

4
您可以使用自定义比较器与Arrays.Sort一起使用,如下所示:
Arrays.Sort(myInfoClass, new Comparator<InfoClass>() {
    @Override
    public int compare(InfoClass o1, InfoClass o2){
        if (o1==null && o2==null) return 0;
        if (o1 == null) return -1;
        if (o2 == null) return 1;
        return o1.distance.compareTo(o2.distance);
    }
});

编辑:空值检查胜利。


4

如果您不想使用 Comparator,并且希望为您的对象提供默认排序,则修改您的类并实现 Comparable 接口也是一个不错的选择。

当您想要为您的对象的数组/集合提供排序时,使用Comparable更加合适。

class InfoClass implements Comparable<InfoClass> {

String name;
String place;
double distance;

@Override
public int compareTo(InfoClass o) {
    return new Double(this.distance).compareTo(new Double(o.distance));
}

然后您可以对它们进行排序

Arrays.sort(myInfoClass)

这是一个很好的答案,特别是如果你计划在代码中的多个位置进行排序。 - Ross Larson
3
你说得对,那是最OO的解决方案。但是我会使用Double.compare(this.distance, o.distance)来进行比较,否则你会创建至少n*log(n)个不必要的对象 :) - lhlmgr
好发现 @lee.O,我没注意到那里。 - Ross Larson

2
Arrays.sort(myInfoClass, new Comparator<InfoClass>() {
  @Override
  public int compare(InfoClass o1, InfoClass o2) {
    return Double.valueOf(o1.distance).compareTo(o2.distance);
  }
});

1

将数组转换为ArrayList,然后使用Collection.sort方法对ArrayList进行排序。


1

同样按降序排序

Arrays.sort(aStudents, Collections.reverseOrder());

Collections在内部定义方法调用

`public static <T> Comparator<T> reverseOrder() {
    return (Comparator<T>) REVERSE_ORDER;
}

公共整数比较(可比较c1,可比较c2){ 返回c2.compareTo(c1); }`


0
希望这个例子能够帮助你根据不同的字段对类对象进行排序。
import java.util.*;
import java.lang.*;
import java.io.*;


public class Main
{
    public static void main ( String [] args) throws IOException
    {

        Employee empList[] = new Employee [4];

        empList[0] = new Employee (8,"Kiran","Developer",15000);
        empList[1] = new Employee (18,"Krishna","DBA",35000);
        empList[2] = new Employee (3,"Pradeep","Tester",25000);
        empList[3] = new Employee (7,"Mithun","Admin",20000);




        Arrays.sort(empList);
        System.out.println("\nAfter Sorting Base On ID");
        for (Employee emp : empList)
            System.out.println(emp);


        Arrays.sort( empList , new EmployeeByDept() );  
        System.out.println("\nAfter Sorting Base On Department");
        for (Employee emp : empList)
            System.out.println(emp);


        Arrays.sort( empList , new EmployeeByName() );  
        System.out.println("\nAfter Sorting Base On Name");
        for (Employee emp : empList)
            System.out.println(emp);


        Arrays.sort( empList , new EmployeeBySalary() );    
        System.out.println("\nAfter Sorting Base On Salary");
        for (Employee emp : empList)
            System.out.println(emp);

    }
}

class EmployeeByDept implements Comparator<Employee>
{
    //compare() is mathod of Comparable Interface
    // Use When we want to sort on other field like Department  
    @Override
    public int compare(Employee emp1, Employee emp2)
    {
        return emp1.getDept().compareTo(emp2.getDept());
    }

}

class EmployeeByName implements Comparator<Employee>
{
    //compare() is mathod of Comparable Interface
    // Use When we want to sort on other field like Department  
    @Override
    public int compare(Employee emp1, Employee emp2)
    {
        return emp1.getName().compareTo(emp2.getName() );
    }

}

class EmployeeBySalary implements Comparator<Employee>
{
    //compare() is mathod of Comparable Interface
    // Use When we want to sort on other field like Department  
    @Override
    public int compare(Employee emp1, Employee emp2)
    {
        return ( emp1.getSalary() - emp2.getSalary());
    }

}



class Employee implements Comparable<Employee> 
{
    int $id  ;
    String $name ;
    String $dept ;
    int $salary ;

    public Employee(int id , String name , String dept , int salary)
    {
        this.$id = id;
        this.$name = name ;
        this.$dept = dept ;
        this.$salary = salary ;
    }


    public int getID () { return this.$id ; }
    public String getName () { return this.$name ; }
    public String getDept () { return this.$dept ; }
    public int getSalary () { return this.$salary ; }

    public String toString()
    {
        return  "[ "
                + "ID :: " + $id 
                + " Name :: " + $name 
                + " Department :: " + $dept 
                + " Salary :: " + $salary  
                + " ]";

    }

    //compareTo() is mathod of Comparable Interface
    //Use when you want natural sorting base on ID , Salary

    @Override
    public int compareTo(Employee emp)
    {
        return (this.$id - emp.$id);
    }


}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接