zoukankan      html  css  js  c++  java
  • java: Comparable比较器,数组对象比较器

    Arrays只适合一个数组/对象内的数值进行比较,

    Comparable比较器(Compara)适合数组,对象,队列等排序,

    Comparable是一个接口类,实现此接口必须复写:compareTo 方法,

    compareTo方法会返回三个值:1,0,-1,可以利用这三个值进行排序

    //比较器
    class Student2 implements Comparable<Student2>{
    	private int strno;
    	private String name;
    	private int age;
    	private float score;
    	
    	
    	
    	public Student2(int strno, String name, int age, float score) {		
    		this.strno = strno;
    		this.name = name;
    		this.age = age;
    		this.score = score;
    	}
    	
    	@Override
    	public String toString() {
    		// TODO 自动生成的方法存根
    		return "学号:"+this.strno+",姓名:"+this.name+",年龄:"+this.age+",成绩:"+this.score;
    	}
    	@Override
    	public int compareTo(Student2 stu) {
    		// TODO 自动生成的方法存根
    		if(this.score > stu.score)
    		{
    			return 1;
    		}else if(this.score < stu.score){
    			return -1;
    		}else{
    			return 0;
    		}
    	}
    	
    	
    }
    
    
    public class CompareDemo {
    
    	public static void main(String args[])
    	{
    		Student2 stu[] = {new Student2(1,"张三",20,98.13f),
    				new Student2(2,"李四",33,88.18f),
    				new Student2(3,"王五",41,80.32f),
    				new Student2(4,"赵六",28,89.77f),
    				new Student2(5,"田七",25,90.53f)};
    		
    		//排序
    				System.out.println("++++++++++++数组排序前+++++++++++++++");
    				print(stu);
    				System.out.println("++++++++++++数组排序后+++++++++++++++");
    				Arrays.sort(stu);
    				print(stu);
    	}
    	
    	public static void print(Student2 stu[])
    	{
    		for(int i=0;i<stu.length; i++)
    		{
    			
    			System.out.println(stu[i]);
    		}
    	}
    	
    }
    

      

  • 相关阅读:
    MySQL 删除有外键约束的表数据
    Python 类装饰器解析
    保持SSH连接的linux服务器不断线
    数字货币交易所常用概念
    Python f-string
    Linux sed命令
    CAS机制详解
    MySQL缓存机制
    PHP网络请求优化
    Java三大特性---继承
  • 原文地址:https://www.cnblogs.com/achengmu/p/6970132.html
Copyright © 2011-2022 走看看