如何将对象数组的值传递给方法

问题描述:

我有一个快速简单的问题,我无法找到答案。如何将对象数组的值传递给方法

我有一个名为quick_srt_int的方法能够对整数数组进行排序,但我的问题是,我的数组是从一个对象形成的,我希望能够从一个特定的子值对数组进行排序(请纠正我关于如何调用)。

只是为了给你一些背景,这是如何声明数组。

student[index] = new Person(name, id, age, gpa); 

我需要能够在不同时间对id,age和gpa进行排序,但不知道如何传递值。我的猜测是我必须这样通过它:

public void ageSort() { 
    quick_srt_int(student[].age, 0, student[].age.length - 1); 
} 

请告诉我如何正确地做到这一点。

我还需要修改快速排序方法来支持double类型的值,因为gpa是双重形式的,我不能将它转换为排序。

任何帮助都非常感谢,非常感谢。

快速排序方法看起来像这样:

public static void quick_srt_int(int array[], int low, int n) { 
    int lo = low; 
    int hi = n; 
    if (lo >= n) { 
     return; 
    } 
    int mid = array[(lo + hi)/2]; 
    while (lo < hi) { 
     while (lo < hi && array[lo] < mid) { 
      lo++; 
     } 
     while (lo < hi && array[hi] > mid) { 
      hi--; 
     } 
     if (lo < hi) { 
      int T = array[lo]; 
      array[lo] = array[hi]; 
      array[hi] = T; 
     } 
    } 
    if (hi < lo) { 
     int T = hi; 
     hi = lo; 
     lo = T; 
    } 
    quick_srt_int(array, low, lo); 
    quick_srt_int(array, lo == low ? lo + 1 : lo, n); 
} 

作为@Logan说,你必须使用比较器或你的Person类必须实现Comparable接口。我给你举个例子:

public class Person implements Comparable { 
    private String name; 
    private int id; 
    private int age; 
    private int gpa; 

    public Person(String name, int id, int age, int gpa) { 
     this.name = name; 
     this.id = id; 
     this.age = age; 
     this.gpa = gpa; 
    } 
    //getters and setters here... 

    //logic for the comparison 
    //NOTE: you can improve the comparison algorithm. 
    public int compareTo (Person p) { 
     //0 means both Person objects are equal. 
     // > 0 means **this** object is greater than p object. 
     // < 0 means **this** object is less than p object. 
     int result = 0; 
     //comparison by id 
     if (this.id > p.id) { 
      result = 1; 
     } else { 
      if (this.id < p.id) { 
       result = -1; 
      } else { //same id, check by age 
       if (this.age > p.age) { 
        result = 1; 
       } else { 
        if (this.age < p.age) { 
         result = -1; 
        } else { //same id and age, check by gpa 
         if (this.gpa > p.gpa) { 
          result = 1; 
         } else { 
          if (this.gpa < p.gpa) { 
           result = -1; 
          } 
         } 
        } 
       } 
      } 
     } 
    } 
    return result; 
} 

而现在,人阵发送到您的快速排序方法:如果要指定此比较功能

public void ageSort() { 
    quick_srt_int(student[], 0, student[].age.length - 1); 
} 

public static void quick_srt_int(Person array[], int low, int n) { 
    //your logic... 
} 

,你需要添加一个参数传递到quick_srt_int函数来设置实现比较器接口的类。

+0

谢谢!我会尝试的。 :) – 2012-02-18 04:30:01

你正在寻找一个Comparator。有一个与您的问题非常相似的示例here

您的人员类需要实施可比较或比较。 example sort by id