阵列函数 java_Java复制阵列– Java中的阵列复制

阵列函数 java

Today we will look into different ways for java array copy. Java provides inbuilt methods to copy the array. Whether you want a full copy or partial copy of the array, you can do it easily using java inbuilt classes.

今天,我们将研究java数组复制的不同方法。 Java提供了内置方法来复制数组。 无论您要数组的完整副本还是部分副本,都可以使用Java内置类轻松完成。

Java复制数组 (Java Copy Array)

java copy array, array copy java

There are many ways to copy array in java. Let’s look at them one by one.


有许多方法可以在Java中复制数组。 让我们一一看一下。

  1. Object.clone(): Object class provides clone() method and since array in java is also an Object, you can use this method to achieve full array copy. This method will not suit you if you want partial copy of the array.

    Object.clone() :Object类提供了clone()方法,并且由于java中的数组也是Object,因此可以使用此方法实现完整的数组复制。 如果要部分复制数组,则此方法不适合您。
  2. System.arraycopy(): System class arraycopy() is the best way to do partial copy of an array. It provides you an easy way to specify the total number of elements to copy and the source and destination array index positions. For example System.arraycopy(source, 3, destination, 2, 5) will copy 5 elements from source to destination, beginning from 3rd index of source to 2nd index of destination.

    System.arraycopy()系统arraycopy()是对数组进行部分复制的最佳方法。 它提供了一种简单的方法来指定要复制的元素总数以及源和目标数组索引位置。 例如, System.arraycopy(source, 3, destination, 2, 5)将5个元素从源复制到目标,从源的第三个索引复制到目标的第二个索引。
  3. Arrays.copyOf(): If you want to copy first few elements of an array or full copy of array, you can use this method. Obviously it’s not versatile like System.arraycopy() but it’s also not confusing and easy to use. This method internally use System arraycopy() method.

    Arrays.copyOf() :如果要复制数组的前几个元素或数组的完整副本,则可以使用此方法。 显然,它不像System.arraycopy()那样通用,但也不易混淆且易于使用。 此方法在内部使用System arraycopy()方法。
  4. Arrays.copyOfRange(): If you want few elements of an array to be copied, where starting index is not 0, you can use this method to copy partial array. Again this method is also using System arraycopy method itself.

    Arrays.copyOfRange() :如果要复制数组的几个元素(起始索引不为0),则可以使用此方法复制部分数组。 同样,此方法也使用系统arraycopy方法本身。

So these are the four most useful methods for full and partial array copy. Note that all these inbuilt methods are to copy one-dimensional arrays only.

因此,这是完整和部分阵列复制的四种最有用的方法。 请注意,所有这些内置方法都仅复制一维数组。

Java复制数组示例 (Java Copy Array Example)

Now let’s see these java array copy methods in action with a simple java program.

现在,让我们看看这些Java数组复制方法在一个简单的Java程序中的作用。

package com.journaldev.util;

import java.util.Arrays;

public class JavaArrayCopyExample {

    /**
     * This class shows different methods for copy array in java
     * @param args
     */
    public static void main(String[] args) {
        int[] source = {1,2,3,4,5,6,7,8,9};
        int[] source1 = {1,2,3};
        int[] destination=null;
        System.out.println("Source array = "+Arrays.toString(source));
        
        destination = copyFirstFiveFieldsOfArrayUsingSystem(source);
        System.out.println("Copy First five elements of array if available. Result array = "+Arrays.toString(destination));
        
        destination = copyFirstFiveFieldsOfArrayUsingSystem(source1);
        System.out.println("Copy First five elements of array if available. Result array = "+Arrays.toString(destination));
        
        destination = copyFullArrayUsingSystem(source);
        System.out.println("Copy full array using System.copyarray() function. Result array = "+Arrays.toString(destination));
        
        destination = copyFullArrayUsingClone(source);
        System.out.println("Copy full array using clone() function. Result array = "+Arrays.toString(destination));
        
        destination = copyFullArrayUsingArrayCopyOf(source);
        System.out.println("Copy full array using Arrays.copyOf() function. Result array = "+Arrays.toString(destination));
        
        destination = copyLastThreeUsingArrayCopyOfRange(source);
        System.out.println("Copy last three elements using Arrays.copyOfRange() function. Result array = "+Arrays.toString(destination));
    }

    /**
     * This method copy full array using Arrays.copyOf() function
     * @param source
     * @return
     */
    private static int[] copyFullArrayUsingArrayCopyOf(int[] source) {
        return Arrays.copyOf(source, source.length);
    }
    
    /**
     * This method copy partial array (last 3 elements) using 
     * Arrays.copyOfRange() function
     * @param source
     * @return
     */
    private static int[] copyLastThreeUsingArrayCopyOfRange(int[] source) {
        //length check is necessary to avoid java.lang.ArrayIndexOutOfBoundsException
        //but for simplicity I am not doing that
        return Arrays.copyOfRange(source, source.length-3, source.length);
    }

    /**
     * This method copy full array using clone() function
     * @param source
     * @return
     */
    private static int[] copyFullArrayUsingClone(int[] source) {
        return source.clone();
    }

    /**
     * This method copy full array using System.arraycopy() function
     * @param source
     * @return
     */
    private static int[] copyFullArrayUsingSystem(int[] source) {
        int[] temp=new int[source.length];
        System.arraycopy(source, 0, temp, 0, source.length);
        return temp;
    }

    /**
     * This method copy full first five elements of array 
     * using System.arraycopy() function
     * @param source
     * @return
     */
    private static int[] copyFirstFiveFieldsOfArrayUsingSystem(int[] source) {
        if(source.length > 5){
            int[] temp=new int[5];
            System.arraycopy(source, 0, temp, 0, 5);
            return temp;
        }else{
            int[] temp=new int[source.length];
            System.arraycopy(source, 0, temp, 0, source.length);
            return temp;
        }
        
    }

}

Output of the above program is:

上面程序的输出是:

Source array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy First five elements of array if available. Result array = [1, 2, 3, 4, 5]
Copy First five elements of array if available. Result array = [1, 2, 3]
Copy full array using System.copyarray() function. Result array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy full array using clone() function. Result array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy full array using Arrays.copyOf() function. Result array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy last three elements using Arrays.copyOfRange() function. Result array = [7, 8, 9]

Java阵列复制–浅复制 (Java Array Copy – Shallow Copy)

Note that all the inbuilt methods discussed above for array copy perform shallow copy, so they are good for primitive data types and immutable objects such as String. If you want to copy an array of mutable objects, you should do it by writing code for a deep copy yourself. Below is a program showing the problem with shallow copy methods.

请注意,上面讨论的所有用于数组复制的内置方法都执行浅表复制,因此它们适用于原始数据类型和不可变对象(例如String)。 如果要复制可变对象的数组,则应自己编写用于深度复制的代码来实现。 下面是一个程序,显示浅拷贝方法的问题。

import java.util.Arrays;

public class JavaArrayCopyMutableObjects {

	public static void main(String[] args) {
		Employee e = new Employee("Pankaj");
		
		Employee[] empArray1 = {e};
		
		Employee[] empArray2 = new Employee[empArray1.length];
				
		System.arraycopy(empArray1, 0, empArray2, 0, empArray1.length);
		
		System.out.println("empArray1 = "+Arrays.toString(empArray1));
		System.out.println("empArray2 = "+Arrays.toString(empArray2));
		
		//Let's change empArray1
		empArray1[0].setName("David");
		
		System.out.println("empArray1 = "+Arrays.toString(empArray1));
		System.out.println("empArray2 = "+Arrays.toString(empArray2));
		
	}

}

class Employee {
	private String name;

	public Employee(String n) {
		this.name = n;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	@Override
	public String toString() {
		return this.name;
	}
}

Now when we run the above program, below is the output produced.

现在,当我们运行上面的程序时,下面是生成的输出。

empArray1 = [Pankaj]
empArray2 = [Pankaj]
empArray1 = [David]
empArray2 = [David]

As you can see that empArray2 got changed too even though it was never the intention. This can cause serious issues in your application, so you are better of writing your own code for deep copying of array. Similar case is there for java object clone method.

正如您所看到的,即使empArray2也从未更改过,但也有所更改。 这可能会在您的应用程序中引起严重的问题,因此最好编写自己的代码以进行数组的深层复制。 java对象克隆方法也有类似情况。

Below is the code for full array copy to use in this case. You can easily write something like this for partial array copy too.

下面是在这种情况下使用的完整数组复制的代码。 您也可以轻松地为部分数组复制编写类似的内容。

import java.util.Arrays;

public class JavaArrayCopyMutableObjects {

	public static void main(String[] args) {
		Employee e = new Employee("Pankaj");
		
		Employee[] empArray1 = {e};
		
		Employee[] empArray2 = fullCopy(empArray1);
		
		System.out.println("empArray1 = "+Arrays.toString(empArray1));
		System.out.println("empArray2 = "+Arrays.toString(empArray2));
		
		//Let's change empArray1
		empArray1[0].setName("David");
		
		System.out.println("empArray1 = "+Arrays.toString(empArray1));
		System.out.println("empArray2 = "+Arrays.toString(empArray2));

		
	}

	private static Employee[] fullCopy(Employee[] source) {
		Employee[] destination = new Employee[source.length];
		
		for(int i=0; i< source.length; i++) {
			Employee e = source[i];
			Employee temp = new Employee(e.getName());
			destination[i] = temp;
		}
		return destination;
	}

}

class Employee {
	private String name;

	public Employee(String n) {
		this.name = n;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	@Override
	public String toString() {
		return this.name;
	}
}

Now when we run the above program, the output produced is:

现在,当我们运行上述程序时,产生的输出为:

empArray1 = [Pankaj]
empArray2 = [Pankaj]
empArray1 = [David]
empArray2 = [Pankaj]

As you can see, in deep copy our source and destination array elements are referring to different objects. So they are totally detached and if we change one of them, the other will remain unaffected.

如您所见,在深度复制中,我们的源数组和目标数组元素引用的是不同的对象。 因此,它们是完全分离的,如果我们更改其中一个,则另一个将不受影响。

That’s all for java copy array and how to properly do array copy in java programs.

这就是Java复制数组以及如何在Java程序中正确进行数组复制的全部内容。

Reference: System class arraycopy documentation

参考: 系统类arraycopy文档

翻译自: https://www.journaldev.com/753/java-copy-array-array-copy-java

阵列函数 java

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值