栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

集合泛型:排成绩

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

集合泛型:排成绩

package demo08.test08;

import java.util.Comparator;
import java.util.TreeSet;

import demo08.test08.Student;

public class TreeSetDemo {

	public static void main(String[] args) {
		// 创建TreeSet集合对象,通过比较器排序进行排序
		TreeSet ts = new TreeSet(new Comparator(){

			@Override
			public int compare(Student s1, Student s2) {
				
				//主要条件:
				int num = s2.getSum() - s1.getSum();
				//次要条件分析:
				int num2 = num==0?s1.getChinese() - s2.getChinese() : num;
				int num3 = num2==0?s1.getName().compareTo(s2.getName()) : num2;
				return num3;
			}			
		});
		//创建学生对象
		Student s1 = new Student("三百七七",100,98);
		Student s2 = new Student("张缤智",100,99);
		Student s3 = new Student("王焕君",99,100);
		Student s4 = new Student("Aurora",98,100);
		Student s5 = new Student("Ethreal",95,95);
		Student s6 = new Student("Ethreal22",95,95);
		//将学生添加到集合
		ts.add(s1);
		ts.add(s2);
		ts.add(s3);
		ts.add(s4);
		ts.add(s5);
		ts.add(s6);
		
		for(Student s : ts){
			System.out.println(s.getName()+","+s.getChinese()+","+s.getMath()+","+s.getSum());
		}
	}

}
public class Student {
	private String name;
	private int chinese;
	private int math;
	
	public Student(){}

	public Student(String name, int chinese, int math) {
		this.name = name;
		this.chinese = chinese;
		this.math = math;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getChinese() {
		return chinese;
	}

	public void setChinese(int chinese) {
		this.chinese = chinese;
	}

	public int getMath() {
		return math;
	}

	public void setMath(int math) {
		this.math = math;
	}
	//成绩过多,对外提供一个求总分的方法
	public int getSum() {
		return this.chinese+this.math;
	}
	
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1032481.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号