Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a copy of an array? [duplicate]

 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.

like image 354
Frightlin Avatar asked Dec 06 '22 03:12

Frightlin


2 Answers

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();
}

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

like image 74
Fedor Skrynnikov Avatar answered Dec 14 '22 21:12

Fedor Skrynnikov


System.arraycopy(students, 0, copyStudents, 0, students.length); 
like image 26
Stewart Avatar answered Dec 14 '22 23:12

Stewart