JAVA如何以数组中的一列作为标准进行排序。

private Student stu[]= {new Student(1,"张三",2),new Student(2,"李四",4),new Student(3,"王五",1),new Student(4,"赵六",0)};

代码如上,如何对上面的stu[]数组第三列从大到小进行排序
输出stu[0]的时候是 李四那一行。

这是对对象数组进行排序,有两种方法:1、一种是实现Comparable接口,复写compareTo()方法。2、另一种是自定义一个比较器即实现Comparator接口,复写compare()方法。


import java.util.Arrays;

import java.util.Comparator;

class Student 

{

public  int id;

public  String name;

public  int age;

public Student(int id,String name,int age){

this.id=id;

this.name=name;

this.age=age;

}

public String toString(){

return "根据第三列排序:"+this.name+".."+this.age;

}

}

class StudentComparator implements Comparator<Student>//定义一个Student比较器

{

public int compare(Student stu1,Student stu2){

if(stu1==stu2){

return 0;

}

if(stu1.age<stu2.age){

return 1;

}else if(stu1.age>stu2.age){

return -1;

}else{

return 0;

}

}

}

public class StudentTest

{

public static void main(String[] args){

Student stu[]= {new Student(1,"张三",2),new Student(2,"李四",4),

new Student(3,"王五",1),new Student(4,"赵六",0)};

StudentComparator sc=new StudentComparator();

Arrays.sort(stu,sc);

for(int i=0;i<stu.length;i++){

System.out.println(stu[i]);

}

}

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-11-25
你这是对对象实现比较大小。这个对对象的编译器肯定不知道。要你自己做好告诉编译器我这个对象是个大的对象。在java中有两种方式
1:实现Comparable 接口 的 public int compareTo(T o) 方法;

2:实现Comparator 接口 的 int compare(T o1, T o2)方法;
在这里你没有贴出你Student类的源码。我就假定只有三个成员变量。如下:

class Student implements Comparable{
private int no, grade;
private String name;
public Student(int no, String name, int grade){
this. no = no;
this.grade = grade;
this.name = name;
}

public int getGrade(){
return grade;
}
//override
public int compareTo(Object arg0){
Student stu = (Student) arg0;
if(this.getGrade()>=arg0.getGrade())
return this.getGrade;
else
return 0;

}
}

然后在你的主函数里面
private Student stu[]= {new Student(1,"张三",2),new Student(2,"李四",4),new Student(3,"王五",1),new Student(4,"赵六",0)};

for(int i = 0 ; i< stu.length-1; i++){
if(stu[i].compareto(stu[i+1]))=0)//如果比较等于0, 说明i<i+1,然后一环
Student student = stu[i];
stu[i] = stu[i+1];
stu[i+1] = student;
}

//// 补充/////
有了比较之后,那就是排序的事情了。 上面写错了。。。。 最起码要用个冒泡排序。 这只是两两一环。。。 。。 不过交换的方法就是上面写的。排序的算法就不写了。。 自己看书就可以啦本回答被网友采纳
相似回答
大家正在搜