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]);
    		}
    	}
    	
    }
    

      

  • 相关阅读:
    序列操作
    上帝造题的七分钟2 / 花神游历各国
    火柴排队
    pair(对组)用法
    线段树
    链上分治
    Rem与Px的转换
    css中单位px和em,rem的区别
    css网页自适应-1
    css网页自适应-2
  • 原文地址:https://www.cnblogs.com/achengmu/p/6970132.html
Copyright © 2011-2022 走看看