Several ways to copy arrays in Java

There are several ways to copy arrays in java:

(1)clone

(2)System.arraycopy

(3)Arrays.copyOf

(4)Arrays.copyOfRange

Here's how to use them:

(1) The clone method is inherited from the Object class. Basic data types (String, boolean, char, byte, short, float, double.long) can be cloned directly using the clone method. Note that the String type is because its value cannot be used. Change so it can be used.

Example of type Int:

`       int a1[]={1,3};
        int a2[]=a1.clone();


        a1[0]=666;
        System.out.println(Arrays.toString(a1));//[666,3]
        System.out.println(Arrays.toString(a2));//[1,3]

String type example

`       String[] a1={"a1","a2"};
        String[] a2=a1.clone();

        a1[0]="b1";//更变a1元素的值


        System.out.println(Arrays.toString(a1));//[b1,a2]
        System.out.println(Arrays.toString(a2));//[a1,a2]

 

(2) The System.arraycopy method is a local method, defined in the source code as follows:

  public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

Parameter meaning:

(Original array, the starting position of the original array, the target array, the starting position of the target array, the number of copies)

Usage example:

`       int  a1[]={1,2,3,4,5};
        int a2[]=new int[10];

        System.arraycopy(a1,1,a2,3,3);
        System.out.println(Arrays.toString(a1));//[1, 2, 3, 4, 5]
        System.out.println(Arrays.toString(a2));//[0, 0, 0, 2, 3, 4, 0, 0, 0, 0]

Note that this method requires us to create a new array ourselves

(3) The bottom layer of Arrays.copyOf actually uses System.arraycopy The source code is as follows:

    public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        @SuppressWarnings("unchecked")
        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;
    }

Parameter meaning:

(Original array, number of copies)

Usage example:

 `       int  a1[]={1,2,3,4,5};
        int a2[]=Arrays.copyOf(a1,3);


        System.out.println(Arrays.toString(a1));//[1, 2, 3, 4, 5]
        System.out.println(Arrays.toString(a2));//[1, 2, 3]

This method does not require us to create a new array

(4) The bottom layer of Arrays.copyOfRange is actually System.arraycopy, but it encapsulates a method

Parameter meaning:

(Original array, start position, number of copies)

Usage example:

`       int  a1[]={1,2,3,4,5};
        int a2[]=Arrays.copyOfRange(a1,0,1);


        System.out.println(Arrays.toString(a1));//[1, 2, 3, 4, 5]
        System.out.println(Arrays.toString(a2));//[1]

The last thing to note is that the copy of the basic type does not affect the value of the original array. If it is a reference type, this cannot be used, because the copy of the array is a shallow copy.

So how to implement deep copying of objects?

(1) Implement the Cloneable interface and rewrite the clone method. Note that a class does not implement this interface, and the clone method cannot be compiled directly by using the clone method.

public class Dog implements Cloneable {

    private String id;
    private String name;
    
    //省略getter / setter
    
    
    
    @Override
    public Dog clone() throws CloneNotSupportedException {

       Dog dog=(Dog)        super.clone();

       return dog;

    }
    
    }

Example:

`       Dog d1=new Dog("1","dog1");
        Dog d2=d1.clone();

        d1.setName("dog1_change");


        System.out.println(d1);//Dog{id='1', name='dog1_change'}
        System.out.println(d2);//Dog{id='1', name='dog1'}

(2) If a class references other classes, and other classes reference other classes, then if you want a deep copy, all classes and their referenced classes must implement the Cloneable interface and override the clone method, so that Since it is very troublesome, the simple method is to make all objects implement the serialization interface (Serializable), and then deeply copy the objects through the serialization method.

   public Dog myclone() {
 6       Dog dog = null;
 7       try { // 将该对象序列化成流,因为写在流里的是对象的一个拷贝,而原对象仍然存在于JVM里面。所以利用这个特性可以实现对象的深拷贝
 8           ByteArrayOutputStream baos = new ByteArrayOutputStream();
 9           ObjectOutputStream oos = new ObjectOutputStream(baos);
10           oos.writeObject(this);
11       // 将流序列化成对象
12           ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
13           ObjectInputStream ois = new ObjectInputStream(bais);
14           dog = (Dog) ois.readObject();
15       } catch (IOException e) {
16           e.printStackTrace();
17       } catch (ClassNotFoundException e) {
18           e.printStackTrace();
19       }
20       return dog;
21   }

Summarize:

This article introduces several ways and usages of array copying in Java, and gives how to implement deep copying of objects in Java. Note that unless necessary, generally do not use deep copying of objects because of poor performance. In addition to the function of implementing deep copy by yourself, there are also some open source tools on the Internet that integrate these functions, such as Apache Common Lang3, but the principles are similar, and interested students can learn it by themselves.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325181078&siteId=291194637