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方法中创建的数组的副本。我不知道该如何解决这个问题。
答案 0 :(得分:7)
public String[] getStudents() {
return Arrays.copyOf(students, students.length);;
}
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了解每种方法的效果。他们是相同的
答案 1 :(得分:1)
System.arraycopy(students, 0, copyStudents, 0, students.length);
答案 2 :(得分:1)
试试这个:
System.arraycopy(students, 0, copyStudents, 0, students.length);
答案 3 :(得分:1)
Java的System
类为此提供了一种实用方法:
public String[] getStudents() {
String[] copyStudents = new String[students.length];
System.arraycopy(students, 0, copyStudents, 0, students.length );
return copyStudents;
}
答案 4 :(得分:0)
System.arraycopy(Object source, int startPosition, Object destination, int startPosition, int length);
答案 5 :(得分:0)
答案 6 :(得分:0)
您可以使用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.