惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
The Blog of Author Tim Ferriss
Hugging Face - Blog
Hugging Face - Blog
F
Fortinet All Blogs
B
Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Security Blog
Microsoft Security Blog
Blog — PlanetScale
Blog — PlanetScale
月光博客
月光博客
腾讯CDC
小众软件
小众软件
G
Google Developers Blog
V
Visual Studio Blog
罗磊的独立博客
GbyAI
GbyAI
V
V2EX
大猫的无限游戏
大猫的无限游戏
H
Help Net Security
L
LangChain Blog
Engineering at Meta
Engineering at Meta
量子位
The GitHub Blog
The GitHub Blog
博客园 - 司徒正美
WordPress大学
WordPress大学
B
Blog RSS Feed

博客园 - simply-zhao

Java 类加载基本原理[转] 浅谈Java内部类的四个应用场景[转--相当不错的文章] Java 局部类/匿名类[转] Java 静态内部类/内部类 Java Serializable Interface [转] Java Immutable Class[ From ] Java Clone机制[转] ANT十五大最佳实践【转】 Ant基础 System.TypeInitializationException C# Foundation---keyword: sealed C# Foundation---keyword: new C# Foundation---indexer C# Foundation---keyword: base & this C# Foundation Series C# Foundation---keyword: abstract & virtual & new & override C# Foundation---keyword: const & readonly & static readonly C# Foundation---keyword extern & P/Invoke [OS Homework] C# Foundation---keyword:static & static constructor
java clone机制
simply-zhao · 2008-04-12 · via 博客园 - simply-zhao

Arrays.copyOf(T[ ] original, int newLength)
System.lang.arraycopy(Object src,  int  srcPos,Object dest, int destPos,int length);
都是浅复制
实际上, 前者是调用了后者:
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
}

例子:
public class Test implements Cloneable{
 private int x;
 public void setX(int x)
 {
  this.x = x;
 }
 public int getX()
 {
  return x;
 }
 
 public Test(int x)
 {
  this.x = x;
 }
 
 public Object clone()
 {
                       try {
                  Test t = (Test)super.clone();  //先执行浅克隆,确保类型正确和基本类型及非可变类类型字段内容正确

                  t.setX(x);
  return t;
                       } catch (CloneNotSupportedException e) {
  e.printStackTrace();
  return null;
       }
 }
}

public static void main(String[] args)
{
     Test[] tests = new Test[3];
     tests[0] = new Test(2);
     tests[1] = new Test(2);
     tests[2] = new Test(2);
     
     Test[] ts = Arrays.copyOf(tests, 3);  //[1]

     tests[0].setX(10);

     for(Test tt : tests)
      System.out.println(tt.getX());
     for(Test t : ts)
      System.out.println(t.getX());
}
输出为:
10
2
2
10
2
2
若将[1]处代码修改为:
     Test[] ts = new Test[3];
     System.arraycopy(tests, 0, ts, 0, 3);
输出依然为:
10
2
2
10
2
2
若将[1]处代码修改为:
     for(int i=0; i<tests.length; i++)
      ts[i] = (Test)tests[i].clone();
输出则为:
10
2
2
2
2
2