首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Java数组排序Arrays_sort,Comparator接口的用法 (2)

2012-12-21 
Java数组排序Arrays_sort,Comparator接口的用法 (二)利用Comparator接口对对象进行排序:?Students类:packa

Java数组排序Arrays_sort,Comparator接口的用法 (二)

利用Comparator接口对对象进行排序:

?

Students类:

package com.seimma.arrays;

public class Students{
?
?private String name;?? //学员姓名
?private int age;?????? //学员年龄
?
?public Students(){
??
?}
?
?public Students(String name,int age){
??this.name=name;
??this.age=age;
?}
?
?public String getName() {
??return name;
?}
?public void setName(String name) {
??this.name = name;
?}
?public int getAge() {
??return age;
?}
?public void setAge(int age) {
??this.age = age;
?}
}

?

ByAgeComparator 排序类:

?

package com.seimma.arrays;

import java.util.Comparator;

public class ByAgeComparator implements Comparator<Object> {
???? /**
????? * firstStudents 要比较的第一个对象
????? * secondStudnets 要比较的第二个对象
????? */
???? public int compare(Object firstStudents, Object secondStudnets) {
??? ? int firstAge=((Students)firstStudents).getAge();????? //取出第一个对象的值。?
????? int secondAge=((Students)secondStudnets).getAge();??? //取出第一个对象的值。

????? int threeAge=firstAge-secondAge;???? //进行比较

????? //第一个参数小于、等于或大于第二个参数时分别返回负整数、零或正整数

????? if (threeAge>0) {
??? ??return 1;
??? ? }
???????? if (threeAge<0) {
??? ??return -1;
??? ? }else {
??? ???? return 0;
??? ? }
??? }
}

?

package com.seimma.arrays;

?

import java.util.Arrays;

public class ArraysDemo {

?????? public static void main(String[] args) {
??????????? ?ArraysDemo sortArrays=new ArraysDemo();
?????????? ??sortArrays.sortObjectArray();
???? ?}

?

????? /**
???? * 对对象进行排序
???? */
??? public void sortObjectArray(){
??? ?Students stu1=new Students("Students1",1);
??? ?Students stu2=new Students("Students2",2);
??? ?Students stu3=new Students("Students3",3);
??? ?Students stu4=new Students("Students4",4);
??? ?Students stu5=new Students("Students5",5);
??? ?Students stu6=new Students("Students6",6);
??? ?
??? ?Students [] stus=new Students[]{stu3,stu5,stu1,stu6,stu2,stu4};
??? ?System.out.println("对对象排序前:");
??? ?for (int i = 0; i < stus.length; i++) {
???Students st=stus[i];
???System.out.println(st.getName());
??}
??? ?
??? ?System.out.println("对对象排序后:");
??? ?Arrays.sort(stus, new ByAgeComparator());
??? ?for (int i = 0; i < stus.length; i++) {
??? ??Students st=stus[i];
??? ??System.out.println(st.getName());
???
??}
??? }

?

}

热点排行