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

      

  • 相关阅读:
    (转)接口100
    (转)WordPress常用模板函数 修改或自制WordPress主题必备
    (转)Memcached 之 .NET(C#)实例分析
    Ubuntu(Linux) + mono + xsp4 + nginx +asp.net MVC3 部署
    urls.py路由系统分发的本质
    Django-缓存
    Django-信号
    MySQL表按月切割
    通过ModelForm实现主机添加和编辑
    字定义JSON序列化支持datetime格式序列化
  • 原文地址:https://www.cnblogs.com/achengmu/p/6970132.html
Copyright © 2011-2022 走看看