学习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循环

原文地址:https://www.cnblogs.com/SirNie/p/13561325.html