Comparable接口
当某个类需要比较式Compare< > ,并其中重写public int compareTo( )
public class Test4 {
public static void main(String[] args) {
Students1[] students1=new Students1[3] ;
students1[0]=new Students1("xiaohong ",21);
students1[1]=new Students1("cindy",14);
students1[2]=new Students1("tom",45);
System.out.println(Arrays.toString(students1));
Arrays.sort(students1);
sort(students1);
System.out.println(Arrays.toString(students1));
}
public static void sort(Comparable[] comparable){
for(int i=0; i<comparable.length;i++){
for(int j=0;j<comparable.length-i-1;j++){
if(comparable[j].compareTo(comparable[j+1])>0) { //compareTo( ) 相等为0 大于返回值大于0 小于返回值小于0
Comparable tmp=comparable[i];
comparable[j]=comparable[j+1];
comparable[j+1]=tmp;
}
}
}
}
}
class Students1 implements Comparable<Students1> {
String name;
int age;
Students1(String name,int age){
this.name=name;
this.age=age;
}
@Override
public String toString() {
//return super.toString();
return "name="+this.name+"age="+this.age;
}
public int compareTo(Students1 o){
return this.age-o.age;// 传进来的参数(xiaohong,21) 与数组中的xiaohong,cindy,tom进行比较 差值越大,数值越大,在通过sort进行排序
}
Cloneable接口
clone( )方法:得到一个对象的副本,也就是从某个对象A创建出另一个与A具有相同状态的B,并且对B 的修改不会影响到A 的状态
返回值为一个新的对象
cloneable接口中没有抽象方法,实际上是一个标识接口,没有任何的接口方法
1.
public class Test4 {
public static void main(String[] args) throws CloneNotSupportedException {
Person1 person1=new Person1("bn",23);
Person1 person12=(Person1)person1.clone();
person12.name="haojie ";
System.out.println(person12.name);
}
}
class Person1 implements Cloneable{
String name;
int age;
Person1(String name,int age){
this.name=name;
this.age=age;
}
protected Object clone() throws CloneNotSupportedException{
Person1 person1=(Person1) super.clone();
return person1;
}
}
2.当了类中包含了一些对象时,就要用到深拷贝,在对对象调用完clone( )方法之后,接着对对象中的非基本诗句类型也要调用clone( )实现深复制class
Person1 implements Cloneable{
String name;
int age;
Money1 money;
Person1(String name,int age ){
this.name=name;
this.age=age;
this.money= new Money1();
}
public Object clone() throws CloneNotSupportedException{
Person1 person1=(Person1) super.clone();
person1.money=(Money1)this.money.clone();
return person1;
}
}
class Money1 implements Cloneable{
public int m=10;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Person1 person1 = new Person1("we", 13);
Person1 person12 =(Person1) person1.clone();
person12.money.m=99;
System.out.println(person1.money.m);
System.out.println(person12.money.m);
浅复制:被复制的对象的所有变量都含有与原对象相同的值,而所有对其他对象的引用任然指向原来的对象,浅赋值仅仅复制所考虑的对象,而不复制他所引用的对象
深复制
被复制的对象的所有变量都含有与原来对象相同的值,除去哪些引用其他对象额变量,哪些引用其他对象的变量将指向被复制的新对象,深复制吧浅复制的对象的引用都复制了一遍