【问题标题】:How to return a copy of an array? [duplicate]如何返回数组的副本? [复制]
【发布时间】:2014-03-08 20:32:14
【问题描述】:
 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 方法中创建的数组的副本。我不知道该怎么做。

【问题讨论】:

标签: java arrays return training-data


【解决方案1】:
System.arraycopy(students, 0, copyStudents, 0, students.length); 

【讨论】:

  • 那么我会说 return copyStudents; ?
【解决方案2】:

1) Arrays.copyOf

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

2System.arraycopy

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

3clone

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

另请参阅answer,了解每种方法的性能。它们几乎一样

【讨论】:

    【解决方案3】:

    试试这个:

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

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        【解决方案5】:
        System.arraycopy(Object source, int startPosition, Object destination, int startPosition, int length);
        

        docu 中的更多信息,当然,在 SO 上已被问过万亿次,例如 here

        【讨论】:

          【解决方案6】:

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

          您也可以使用System.arraycopy()

          【讨论】:

            【解决方案7】:

            您可以使用Arrays.copyOf()

            例如:

            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.
            

            【讨论】:

              猜你喜欢
              • 2017-01-14
              • 1970-01-01
              • 2011-07-14
              • 1970-01-01
              • 2011-09-25
              • 1970-01-01
              • 2014-02-09
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多