您好,欢迎来到爱问旅游网。
搜索
您的当前位置:首页java中自定义比较器

java中自定义比较器

来源:爱问旅游网

java中自定义比较器

package lesson01;

import java.util.Arrays;
import java.util.Comparator;

public class demo04_Comparator {

	public static void main(String[] args) {
		student s1 = new student("A", 2, 23);
		student s2 = new student("B", 1, 21);
		student s3 = new student("C", 3, 22);

		student stuents[] = { s1, s2, s3 }; // 自定义学生数组,将学生对象扔进去
		printStudents(stuents);
		Arrays.sort(stuents, new IdAscendingComparator());
		printStudents(stuents);
	}

	public static void printStudents(student[] students) {
		for (student student : students) {
			System.out.println("Name : " + student.name + ", Id : " + student.id + ", Age : " + student.age);
		}
		System.out.println("===========================");
	}

}

// 自定义升序比较类,实现比较规则
class IdAscendingComparator implements Comparator<student> {
	// 升序
	@Override
	public int compare(student s1, student s2) {
		return s1.id - s2.id;
	}

}

// 自定义降序比较类,实现比较规则
class IdDescendingComparator implements Comparator<student> {
	// 降序
	@Override
	public int compare(student s1, student s2) {
		return s2.id - s1.id;
	}

}

class student {
	String name;
	int id;
	int age;

	public student(String name, int id, int age) {
		super();
		this.name = name;
		this.id = id;
		this.age = age;
	}

}

Name : B, Id : 1, Age : 21
Name : A, Id : 2, Age : 23
Name : C, Id : 3, Age : 22
====================
Name : C, Id : 3, Age : 22
Name : A, Id : 2, Age : 23
Name : B, Id : 1, Age : 21
====================

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- awee.cn 版权所有 湘ICP备2023022495号-5

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务