Home >Java >javaTutorial >What is the deep copy method of one-dimensional array in java

What is the deep copy method of one-dimensional array in java

王林
王林forward
2023-05-03 17:43:071272browse

1. Three methods

(1) Call clone

(2) Call System.arraycopy

The above two methods are suitable for basic types The effect is the same as object type data.

(3) Use a FOR loop to copy each element of the array. (Pay attention to calling the clone method)

2. Example

       Object[] src = new Object[]{ new String("Zhao"),
                                        Integer.valueOf(1),
                                        Integer.valueOf(2),
                                        Integer.valueOf(3),
                                        Integer.valueOf(4)};                               
       Object[] dest = src.clone();                //1.拷贝数据       
        // Object[] dest = new Object[5];
        // System.arraycopy(src, 0, dest, 0, dest.length);       
        System.out.println( dest.equals(src));
       System.out.println( dest == src );
       for (int i = 0; i < dest.length; i++) {
           System.out.print( dest[i]+", " );     
           dest[i] = new String("KE");               //2.改变新数组内容                  
            System.out.print( dest[i]+", " );        
            System.out.println( src[i]+",");          //3.不影响原始数组
        }
       System.out.println();

Note: A deep copy in a one-dimensional array is only a shallow copy in a multi-dimensional array.

The above is the detailed content of What is the deep copy method of one-dimensional array in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete