接口小总结(五)

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

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值