Comparable和Cloneable接口的使用

(一)Comparable接口

public interface Comparable<T>
  • 参数类型 :T - 可以将此对象与之进行比较的对象类型

  • 该接口对实现它的每个类的对象强加一个整体排序。 这个排序被称为类的自然排序 ,类的compareTo方法被称为其自然比较方法

  • Collections.sort (和Arrays.sort )可以自动对实现此接口的对象进行列表(和数组)排序。(实现该接口的对象,可以使用如在键sorted map或作为在元件sorted set ,而不需要指定一个comparator )

  • Arrays.sort()–》排序

  • 如果要排序自定义类型,需要自己自动动手实现comparable接口

接口的实现:

class Student implements Comparable<Student>{
    public String name;
    public int age;
    public double score;
    public Student(String name,int age,double score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                '}';
    }
    @Override
    public int compareTo(Student o) {
        return this.age - o.age;
        //return this.name.compareTo(o.name);
        //return (int)(this.score - o.score);
    }
}

测试:

public class TestDemo {
    public static void main(String[] args) {
        Student[] student = new Student[3];
        student[0] = new Student("chenyi",21,99.9);
        student[1] = new Student("buyi",10,78.9);
        student[2] = new Student("mubai",18,89.9);
        Arrays.sort(student);
        System.out.println(Arrays.toString(student)); 
    }
}

结果:
[Student{name=‘mubai’, age=18, score=88.9}, Student{name=‘chenyi’, age=21, score=99.8}, Student{name=‘buyi’, age=24, score=78.9}]

(二)Cloneable接口

public interface Cloneable
  • 一个类实现Cloneable接口,以指示Object.clone()方法,该方法对于该类的实例进行现场复制是合法的

接口实现:

class Money implements Cloneable{
    double money = 12.5;
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
class Person implements Cloneable{
    public String name;
    public Money m;
    public Person() {
        this.m = new Money();
    }
    @Override
    protected Object clone() throws CloneNotSupportedException{
        //return super.clone();
        Person per = (Person) super.clone();
        per.m = (Money)this.m.clone();
        return per;
    }
}

测试:

public class TestDemo2 {
    public static void main(String[] args) throws CloneNotSupportedException{
        Person person = new Person();
        Person person2 = (Person)person.clone();
        person2.m.money = 99.9;
        System.out.println(person.m.money);
        System.out.println(person2.m.money);
    }
}

结果:
12.5
99.9

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值