深拷贝 [] 和 ArrayList Java [英] Deep Copy [] and ArrayList Java

查看:24
本文介绍了深拷贝 [] 和 ArrayList Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对一些 Object[] 和 ArrayList 进行深度复制我该怎么做(不循环,并调用克隆)

I want to make a Deep Copy of some Object[] and ArrayList How can i do that (without looping , and calling clone)

没有用于执行此操作的标准工具?

There aren't standard utils for doing this?

谢谢若昂

推荐答案

没有任何平凡的对象需要提供一些来支持复制:即使是以实现 Clone 或 Serialize 的形式.这或多或少是没有内置方法并且循环不可避免的原因.

None trivial objects need to provide some to support copying: even if that is in the form of implementing Clone or Serialize. This is more or less why there is no built in method and the loop is unavoidable.

如果它都是你自己的代码,那么我会推荐一个复制构造函数而不是克隆或序列化/反序列化,因为这更面向对象;您要求对象创建自己的副本,而不是要求 JVM 进行低级复制.这样的代码非常简单易读,因此希望从长远来看维护成本更低:

If it is all your own code then I would recommend a copy constructor over either clone or serialize/deserialize as that is more OO; you ask the object to create its own copy rather than ask the JVM to do a low level copy. Such code is very simple and easy to read so hopefully cheaper to maintain in the long run:

public class Widget {
   private int x = 0;
   public Widget(Widget copyMe){
       this.x = copyMe.x;
       // ...
   }
   // ....
}

当然,您仍然需要一个循环来循环调用复制构造函数来填充新集合的旧集合.有一本名为 Effective Java 的书,其中详细介绍了我强烈推荐的克隆和序列化的陷阱.

You still need a loop of course to loop over the old collection invoking the copy constructor to populate the new collection. There is a book called Effective Java which goes into a lot of detail about the pitfalls of clone and serialize that I highly recommend.

有些系统确实需要非常高速的复制和排序等(例如 Hadoop).这样的系统让开发人员有责任支持自定义二进制格式(例如 byte[] getAsBytes()/public Widget(byte[] fromBytes) ).将许多转换为 byte[] 的对象打包到一个更大的数组中意味着可以在大数组上使用 System.arraycopy 非常快速地一次性复制它们.JVM 会将 System.arraycopy 作为低级内存复制.在复制之后,您仍然需要循环从字节块中反序列化对象.

There are some systems which really need very high speed copying and sorting and the like (e.g. Hadoop). Such systems put the onus on the developer to support a custom binary format (e.g. byte[] getAsBytes() / public Widget(byte[] fromBytes) ). Packing many objects turned into byte[] into a larger array means that they can be all copied at once very fast using System.arraycopy on the big array. The JVM is going to do System.arraycopy as a low level memory copy. You are still going to need the loop to deserialize the objects from the chunk of bytes after the copy.

一般来说,编译器和 jvm 倾向于很好地优化基本代码,所以除非你实际测量到你有一个真实且可测量的性能问题,否则一个非常简单的循环和一个非常可读的复制构造函数将是最好的长期方法.

In general the compiler and jvm tend to optimize basic code very well so unless you actually measure that you have a real and measurable performance issue then a very simple loop with a very readable copy constructor is going to be the best long term approach.

这篇关于深拷贝 [] 和 ArrayList Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆