zoukankan      html  css  js  c++  java
  • java之标记型接口Cloneable

    1、克隆用途。

    Cloneable和Serializable一样都是标记型接口,它们内部都没有方法和属性,implements Cloneable表示该对象能被克隆,能使用Object.clone()方法。如果没有implements Cloneable的类调用Object.clone()方法就会抛出CloneNotSupportedException。

    2、克隆分类。

    (1)浅克隆(shallow clone),浅拷贝是指拷贝对象时仅仅拷贝对象本身和对象中的基本变量,而不拷贝对象包含的引用指向的对象。 
    (2)深克隆(deep clone),深拷贝不仅拷贝对象本身,而且拷贝对象包含的引用指向的所有对象。

    举例区别一下:对象A1中包含对B1的引用,B1中包含对C1的引用。浅拷贝A1得到A2,A2中依然包含对B1的引用,B1中依然包含对C1的引用。深拷贝则是对浅拷贝的递归,深拷贝A1得到A2,A2中包含对B2(B1的copy)的引用,B2中包含对C2(C1的copy)的引用。

    3、克隆举例。

    要让一个对象进行克隆,其实就是两个步骤: 

    (1)让该类实现java.lang.Cloneable接口; 
    (2)重写(override)Object类的clone()方法。

    4、浅克隆举例。

    5、深克隆举例。

    publicclass Wife implements Cloneable {privateint id; private String name; publicintgetId() { return id; } publicvoidsetId(int id) { this.id = id; } public String getName() { return name; } publicvoidsetName(String name) { this.name = name; } publicWife(int id,String name) { this.id = id; this.name = name; } @OverridepublicinthashCode() {//myeclipse自动生成的 finalint prime = 31; int result = 1; result = prime * result + id; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Overridepublicbooleanequals(Object obj) {//myeclipse自动生成的 if (this == obj) returntrue; if (obj == null) returnfalse; if (getClass() != obj.getClass()) returnfalse; Wife other = (Wife) obj; if (id != other.id) returnfalse; if (name == null) { if (other.name != null) returnfalse; } elseif (!name.equals(other.name)) returnfalse; returntrue; } @Overridepublic Object clone() throws CloneNotSupportedException { returnsuper.clone(); } /** * @param args * @throws CloneNotSupportedException */publicstaticvoidmain(String[] args) throws CloneNotSupportedException { Wife wife = new Wife(1,"wang"); Wife wife2 = null; wife2 = (Wife) wife.clone(); System.out.println("class same="+(wife.getClass()==wife2.getClass()));//true System.out.println("object same="+(wife==wife2));//false System.out.println("object equals="+(wife.equals(wife2)));//true } }

  • 相关阅读:
    Android composite adb interface
    android自适应屏幕方向和大小
    Android音频介绍
    android如何播放和录制音频
    Android中解决图像解码导致的OOM问题
    android 图片占用内存与什么有关
    int android.graphics.Bitmap.getRowBytes()
    Thymeleaf select 反显 默认选中
    淘宝H5 sign加密算法
    c# 菜鸟包裹查询
  • 原文地址:https://www.cnblogs.com/igoodful/p/9364027.html
Copyright © 2011-2022 走看看