Set案例

案例1:成绩排序

需求:用TreeSet存储多个学生信息(姓名,语文成绩,数学成绩),并遍历该集合
要求:按照总分从高到低出现
思路:

  1. 定义学生类
package itheima;

public class Student{
	private String name;
	private  int chinese;
	private  int math;
	
	public Student() {
		
	}
	public Student(String name,int chinese,int math){
		this.chinese= chinese;
	 this.math =math;
	 this.name =name;
		
	}	
		public void setName(String name) {
	    	this.name=name;
	    }
	    public void setChinese(int chinese) {
	    	this.chinese= chinese;
	    	
	    }
	    public void setMath(int math) {
	    	this.math =math;
	    	
	    }
	    public String getName() {return name;}
	    public int  getChinese() {return chinese;}
	    public int getMath() {return math;}
	    
	    public int getSum() {
	    	return this.chinese+this.math;
	    }
}

  1. 创建TreeSet集合对象,通过比较器进行排序
  2. 创建学生对象
  3. 把学生对象添加到集合
  4. 遍历集合
package itheima;

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

public class TreeSetDemo {
	public static void main(String[] args) {
		//创建TreeSet集合对象,通过比较器排序进行排序
		TreeSet<Student> ts =new TreeSet<Student>(new Comparator<Student>() {
			@Override
			public int compare(Student s1, Student s2) {
//			int num=(s2.getChinese()+s2.getMath())-(s1.getChinese()+s1.getMath());
		//主要条件
				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("小红",67,90);
		Student s2 =new Student("小看",90,46);
		Student s3 =new Student("小可",67,100);
		Student s4=new Student("小将",87,80);
		Student s5=new Student("小来",44,99);
		
		Student s6=new Student("大明",99,44);
		Student s7=new Student("赵宇",99,44);
		
		ts.add(s5);
		ts.add(s4);
		ts.add(s3);
		ts.add(s2);
		ts.add(s6);
		ts.add(s7);
		
		for(Student s:ts) {
			System.out.println(s.getChinese()+","+s.getMath()+","+s.getName()+","+s.getSum());
			
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值