相等及拷贝
- ==
- equal
- clone()
- Cloneable
- 原型模型
一 ==
==是比较地址,若两个对象用==连接返回true,那他们肯定是同一个对象;
二 equal
equal默认比较的是地址,但是任何函数都可以重载equal()函数,最著名的重载是String.equal(),String将地址比较重载为值比较。
三 clone() protected
x.clone() != x
-
will be true, and that the expression:
x.clone().getClass() == x.getClass()
true
, but these are not absolute requirements. While it is typically the case that:x.clone().equals(x)
true
, this is not an absolute requirement.
四 cloneable
Java的cloneable是Java对象的一种拷贝技术,类似于serializable。在Java中,所有的对象都是存储与堆中的,cloneable就是在堆中新建一个与原来对象完全相同的对象。Java中实现cloneable有以下几个步骤:
一、要进行clone的类必须实现Cloneable接口
二、如果有必要,重写Object类的clone()方法。
三、在重写的clone()方法中,注意类所引用对象的深拷贝与浅拷贝问题。
示例代码:
- package com.example.cloneable;
- public class User implements Cloneable {
- /**
- * User id
- */
- private int id;
- /**
- * User name
- */
- private String name;
- /**
- * User age
- */
- private int age;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- @Override
- protected Object clone() throws CloneNotSupportedException {
- return super.clone();
- }
- }
- package com.example.cloneable;
- public class Administrator implements Cloneable {
- private User user;
- /**
- * @param args
- * @throws CloneNotSupportedException
- */
- public static void main(String[] args) throws CloneNotSupportedException {
- Administrator administrator = new Administrator();
- administrator.setUser(new User());
- Administrator administrator2 = (Administrator)administrator.clone();
- System.out.println(administrator == administrator2);<span style="white-space:pre"> </span> #false
- System.out.println(administrator.getUser() == administrator2.getUser()); #false
- }
- public void setUser(final User user) {
- this.user = user;
- }
- public User getUser() {
- return this.user;
- }
- @Override
- protected Object clone() throws CloneNotSupportedException {
- Administrator administrator = (Administrator)super.clone();
- administrator.user = (User)this.user.clone(); //此处为深拷贝
- return administrator;
- }
五 原型模型
为了获取对象的一份拷贝,我们可以利用Object类的clone()方法。
在派生类中覆盖基类的clone()方法,并声明为public。切记clone()返回为Object类型,需要进行强制转换。
在派生类的clone()方法中,调用super.clone()。
在派生类中实现Cloneable接口。Cloneable接口没有定义任何抽象方法,实现该接口只是通知系统该对象支持clone,这样的接口我们称之为“标识接口”。