What is the most effective way to copy an array?.
sobes.tech AI
Answer from AI
The most efficient methods for primitive data types and objects without deep copying are:
-
System.arraycopy(): A native method optimized for fast copying.// Example of using System.arraycopy int[] sourceArray = {1, 2, 3, 4, 5}; int[] destinationArray = new int[sourceArray.length]; System.arraycopy(sourceArray, 0, destinationArray, 0, sourceArray.length); -
Arrays.copyOf(): A convenient method from theArraysclass. It internally usesSystem.arraycopy().// Example of using Arrays.copyOf int[] sourceArray = {1, 2, 3, 4, 5}; int[] destinationArray = Arrays.copyOf(sourceArray, sourceArray.length);
For deep copying objects (when you need to copy not only references but also the objects they point to), other approaches may be required, such as:
-
Implementing the
Cloneableinterface and overriding theclone()method. Not recommended for new development due to numerous issues.// Example of implementing Cloneable and clone() class MyObject implements Cloneable { int value; MyObject innerObject; @Override protected Object clone() throws CloneNotSupportedException { MyObject cloned = (MyObject) super.clone(); // deep copy of the inner object cloned.innerObject = (MyObject) this.innerObject.clone(); return cloned; } } -
Using a copy constructor.
// Example of a copy constructor class MyObject { int value; MyObject innerObject; public MyObject(MyObject other) { this.value = other.value; // deep copy of the inner object this.innerObject = new MyObject(other.innerObject); } } -
Using serialization/deserialization (e.g., with
ByteArrayInputStreamandObjectInputStream). May be inefficient for large arrays or objects that do not implementSerializable. -
Using third-party libraries (e.g., Apache Commons Lang with
SerializationUtils.clone()).
The most effective method for shallow (surface) copying of primitive types and simple objects is System.arraycopy() or Arrays.copyOf(). For deep copying, a copy constructor is often preferred.