4
 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.

Frightlin
  • 161
  • 1
  • 2
  • 14

7 Answers7

12

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

Community
  • 1
  • 1
Fedor Skrynnikov
  • 5,521
  • 4
  • 28
  • 32
1
System.arraycopy(students, 0, copyStudents, 0, students.length); 
Stewart
  • 17,616
  • 8
  • 52
  • 80
1

try this:

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

Java's System class provides a utility method to this:

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

    return copyStudents;
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0
System.arraycopy(Object source, int startPosition, Object destination, int startPosition, int length);

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

Community
  • 1
  • 1
1ac0
  • 2,875
  • 3
  • 33
  • 47
0

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

OR

You can also use System.arraycopy().

Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
0

You can use 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.
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115