(一)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