zoukankan      html  css  js  c++  java
  • 学习java第51天

    1.Comparable 接口的定义:

    public interface Comparable<T>{

        public int compareTo(T o)

    }

    接口中只有一个 compareTo 方法,该方法返回一个 int 类型的数据,但是 int 的值只能是3种:

    *1:表示大于

    *-1:表示小于

    *0:表示相等

    //设计一个学生类,包含姓名、年龄、成绩,并产生一个对象数组,要求按成绩由高到底排序,如果成绩相等,则按年龄由低到高排序

    import java.util.Arrays;

    class Student implements Comparable<Student>{

        private 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 + " " + age + " " + score;

        }

        public int compareTo(Student stu){

            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 Root{

        public static void main(String[] args) {

            Student[] stu = {new Student("stu1",20,90.0f),

            new Student("stu2",22,90.0f),

            new Student("stu3",20,70.0f),

            new Student("stu4",34,98)};

            Arrays.sort(stu);

            for (Student x:stu){

                System.out.println(x);

            }

        }

    }

    实现Comparable接口的类,不能排序

    //对Person类进行排序

    import.java.util.HashSet;

    import.java.util.Set;

    piblic class ComparaDemo {

     public static void main(String[] args) {

      Set<Person> set = new HashSet<Person>();

      set.add(new Person("张三",20));

      set.add(new Person("李四",21));

      set.add(new Person("王五",22));

      System.out.println(set);

     }

    }

    2.明天学习内容:增强for循环

  • 相关阅读:
    对于程序员来说,如何才能快速转行赶上大数据这辆高铁呢?
    大数据学习计划
    大数据学习详细路线
    大数据到底要怎么学习?
    大数据处理技术怎么学习呢?
    从零开始大数据学习路线
    大数据从入门到精通
    大数据学习路线
    8.【Spring Cloud Alibaba】配置管理-Nacos
    7.【Spring Cloud Alibaba】微服务的用户认证与授权
  • 原文地址:https://www.cnblogs.com/SirNie/p/13561325.html
Copyright © 2011-2022 走看看