Java自学--比较器

来源:互联网 发布:免费域名 空间 编辑:程序博客网 时间:2024/05/20 23:31

Array函数

import java.util.* ;public class ArraysDemo{public static void main(String arg[]){int temp[] = {3,4,5,7,9,1,2,6,8} ;// 声明一个整型数组Arrays.sort(temp) ;// 进行排序的操作System.out.print("排序后的数组:") ;System.out.println(Arrays.toString(temp)) ;// 以字符串输出数组// 如果要想使用二分法查询的话,则必须是排序之后的数组int point = Arrays.binarySearch(temp,3) ;// 检索位置System.out.println("元素‘3’的位置在:" + point) ;Arrays.fill(temp,3);// 填充数组System.out.print("数组填充:") ;System.out.println(Arrays.toString(temp)) ;}};



比较器之Compareble接口的使用

class Student implements Comparable<Student> {// 指定类型为Studentprivate String name ;private int age ;private float score ;public Student(String name,int age,float score){this.name = name ;this.age = age ;this.score = score ;}public String toString(){return name + "\t\t" + this.age + "\t\t" + this.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 ;}}}};public class ComparableDemo01{public static void main(String args[]){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]) ;}}};

比较器之Comparator

import java.util.* ;class Student{// 指定类型为Studentprivate String name ;private int age ;public Student(String name,int age){this.name = name ;this.age = age ;}public boolean equals(Object obj){// 覆写equals方法if(this==obj){return true ;}if(!(obj instanceof Student)){return false ;}Student stu = (Student) obj ;if(stu.name.equals(this.name)&&stu.age==this.age){return true ;}else{return false ;}}public void setName(String name){this.name = name ;}public void setAge(int age){this.age = age ;}public String getName(){return this.name ;}public int getAge(){return this.age ;}public String toString(){return name + "\t\t" + this.age  ;}};class StudentComparator implements Comparator<Student>{// 实现比较器// 因为Object类中本身已经有了equals()方法public int compare(Student s1,Student s2){if(s1.equals(s2)){return 0 ;}else if(s1.getAge()<s2.getAge()){// 按年龄比较return 1 ;}else{return -1 ;}}};public class ComparatorDemo{public static void main(String args[]){Student stu[] = {new Student("张三",20),new Student("李四",22),new Student("王五",20),new Student("赵六",20),new Student("孙七",22)} ;java.util.Arrays.sort(stu,new StudentComparator()) ;// 进行排序操作for(int i=0;i<stu.length;i++){// 循环输出数组中的内容System.out.println(stu[i]) ;}}};


0 0
原创粉丝点击