Comparator 接口
Arrays.sort的第二个版本,有一个数组和一个比较器作为参数,比较器是实现了Comparator接口的类的实例。
public interface Comparator<T>
{
int compare (T first,T second);
}
按照字符段的长度进行比较。
class one implements Comparator<String>
{
public int compare(String first,String second)
{
return first.length()-second.length();
}
}
调用Arrays.sort方法。
String sd[]={"pkl","hhhhh","nb"};
Arrays.sort(sd,new one());
对象克隆
下面会讨论Cloneable接口,实现clone方法对对象进行克隆。
为什么会对对象克隆?
考虑以下情况:
var one=new Student(177);//177为身高。
Student two=one;
two.height(10);//将two对象的身高增加10cm;
System.out.println(one.heigh);//187cm;
原因就是one和two引用的是同一个对象(只new 了一个对象,有one,two两个对象引用)
var one=new Student(177);//177为身高。
Student three=one.clone();//新建了一个对象。
three.height(10);
System.out.println(three.heigh);//177cm;one和three引用的是不同的对象。
下面详解克隆拷贝的两种形式:浅拷贝和深拷贝。
设有以下类:
public class school
{
public String name;
public int year;
public student one;//student为一个类的类型。
......//实例变量的构造器和访问器方法。
}
浅拷贝:(默认情况下为浅拷贝)
var two=new school(......);
school three=two.clone();//浅拷贝。
基本类型数据(int等)two与three各有一份。
其他对象的引用(String和student)two与three 共享。
深拷贝:(基本类型和对象引用都进行拷贝)。
对于每一个类,需要确定:
1.默认的clone方法(浅拷贝)是否满足需要;
2.是否可以在可变的子对象上调用clone来覆盖默认的clone方法;(即调用是否调用深拷贝)
3.是否不该使用clone。
如果类进行深拷贝,类必须:
1.实现Cloneable接口;
2.重新定义clone方法,并指定public访问修饰符。
即使浅拷贝能满足需要,还是需要实现Cloneable接口,将clone定义为public,再调用super.clone()。例:
class student implements Cloneable
{
public student clone()throws CloneNotSupportedException
{
return (student)super.clone();
}
}