This question already has answers here:
Make copy of an array

(11 个回答)


7年前关闭。



 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;

}

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

最佳答案

1) Arrays.copyOf

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

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

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

另请参阅关于每种方法性能的 answer。他们很相似

关于java - 如何返回数组的副本?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21695358/

10-09 19:51