Java 如何返回数组的副本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21695358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:07:02  来源:igfitidea点击:

How to return a copy of an array?

javaarraysreturntraining-data

提问by Frightlin

 public void addStudent(String student) {
    String [] temp = new String[students.length * 2];
    for(int i = 0; i < students.length; i++){
    temp[i] = students[i];
        }
    students = temp;
    students[numberOfStudents] = student;
    numberOfStudents++;

 }


public String[] getStudents() {
    String[] copyStudents = new String[students.length];

    return copyStudents;

}

I'm trying to get the method getStudents to return a copy of the array that I made in the addStudent method. I'm not sure how to go about this.

我试图让方法 getStudents 返回我在 addStudent 方法中创建的数组的副本。我不知道该怎么做。

采纳答案by Fedor Skrynnikov

1) Arrays.copyOf

1) Arrays.copyOf

public String[] getStudents() {
   return Arrays.copyOf(students, students.length);;
}

2 System.arraycopy

2 System.arraycopy

public String[] getStudents() {
   String[] copyStudents = new String[students.length];
   System.arraycopy(students, 0, copyStudents, 0, students.length); 
   return copyStudents;
}

3 clone

3克隆

public String[] getStudents() {
   return students.clone();
}

Also see the answerabout performance of each approach. They are pretty the same

另请参阅有关每种方法性能的答案。他们很相似

回答by Stewart

System.arraycopy(students, 0, copyStudents, 0, students.length); 

回答by Fedor Skrynnikov

try this:

尝试这个:

System.arraycopy(students, 0, copyStudents, 0, students.length);

回答by Mureinik

Java's Systemclass provides a utility method to this:

Java 的System类为此提供了一个实用方法:

public String[] getStudents() {
    String[] copyStudents = new String[students.length];
    System.arraycopy(students, 0, copyStudents, 0, students.length );

    return copyStudents;
}

回答by 1ac0

System.arraycopy(Object source, int startPosition, Object destination, int startPosition, int length);

More information in docuand of course, have been asked trilion times here on SO, for example here

更多信息实况,当然,已被要求trilion次在这里SO,例如这里

回答by Ankur Shanbhag

You can use Arrays.copyOf()to create a copy of your array.

您可以使用Arrays.copyOf()创建数组的副本。

OR

或者

You can also use System.arraycopy().

您还可以使用System.arraycopy()

回答by Ruchira Gayan Ranaweera

You can use Arrays.copyOf().

您可以使用Arrays.copyOf()

Eg:

例如:

int[] arr=new int[]{1,4,5}; 
Arrays.copyOf(arr,arr.length); // here first argument is current array
                               // second argument is size of new array.