zoukankan      html  css  js  c++  java
  • Comparable接口

    java.util.Arrays类也可以对Object数组进行排序,但是要使用这种方法排序必须实现Comparable接口,此接口就是用于指定对象排序规则的。

    设计一个学生类,成绩由高到低排序,成绩相等,按年龄由低到高排序。

    //=================================================
    // File Name       :	Array_demo
    //------------------------------------------------------------------------------
    // Author          :	Common
    
    // 类名:student_
    // 属性:
    // 方法:
    class student_ implements Comparable<student_>{
    	private String name;
    	private int age;
    	private float score;
    	
    	public student_(String name, int age, float score) {
    		super();
    		this.name = name;
    		this.age = age;
    		this.score = score;
    	}
    
    	@Override
    	public String toString() {
    		return "Student [name=" + name + ", age=" + age + ", score=" + score + "]";
    	}
    	
    	public int compareTo(student_ stu){		//覆写compareTo()方法,实现排序规则的应用
    		if(this.score>stu.score){
    			return -1;
    		}else if(this.score<stu.score){
    			return 1;
    		}else{
    			if(this.age>stu.age){
    				return 1;
    			}else if(this.age<stu.age){
    				return -1;
    			}else{
    				return 0;
    			}
    		}
    	}
    	
    }
    
    //主类
    //Function        : 	Comparable_demo
    public class Comparable_demo {
    
    	public static void main(String[] args) {
    		// TODO 自动生成的方法存根
    		student_ stu[] = {new student_("张三",20,90.0f),new student_("李四",22,90.0f),
    				new student_("王五",20,99.0f),new student_("赵六",20,70.0f),
    				new student_("孙七",22,100.0f)};
    		java.util.Arrays.sort(stu);
    		for(int i=0;i<stu.length;i++){
    			System.out.println(stu[i]);
    		}
    	}
    
    }
    
  • 相关阅读:
    layoutSubviews总结
    Vue.js:循环语句
    Vue.js:条件与循环
    Vue.js:模版语法
    Vue.js:起步
    Vue.js-Runoob:目标结构
    Vue.js-Runoob:安装
    Runoob-Vue.js:教程
    Vue.js:template
    培训-Alypay-Cloud:蚂蚁金融云知识点
  • 原文地址:https://www.cnblogs.com/tonglin0325/p/5270161.html
Copyright © 2011-2022 走看看