I've created the class Course
which contains the array students
. This array contains student names which are in string form.
My new goal is to convert from an Array to an ArrayList. I'm not really sure how to go about this. I've read up on ArrayList and I believe it's resize-able which I think would work well in this case given the fact that the number of students might change constantly with my dropSutdent
and addStudent
method as opposed to setting an array size to 100, but only having 20 students.
I'd really appreciate and explanations/suggestions of how exactly to change to an ArrayList instead of an Array.
Note I apologize for any mistakes or if I left something unclear. This is my first question on StackOverflow and I know you guys are pretty strict on question asking, so I apologize in advance.*
class Course {
private String courseName;
private String[] students = new String[100];
private int numberOfStudents;
public Course(String courseName) {
this.courseName = courseName;
}
public void addStudent(String student) {
int add = numberOfStudents - students.length; //Create integer to find how many slots we need
if (numberOfStudents > students.length) { //if # of students is bigger then size of array,
String[] array = new String[students.length + add]; //then we add slots to the array.
System.arraycopy(students, 0, array, 0, students.length); //copy array
students = array;
}
students[numberOfStudents++] = student; //add student.
}
public String[] getStudents() {
return students;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public String getCourseName() {
return courseName;
}
public void dropStudent(String student) {
for (int i = 0; i < students.length; i++) {
if (student == (students[i])) { //If student matches the student we want to remove.
numberOfStudents--; //remove student
while (i < numberOfStudents) {
students[i] = students[i+1];
i++;
}
}
}
}
public void clear() {
students = new String[1]; //set size to 1
numberOfStudents--; //remove all students
}
}
private String[] students = new String[100];
to thisList<String> students = new ArrayList<>();
then youraddStudent
method will internally call the listadd
method and thedropStudent
will internally call the listremove
method. also don't compare strings like thisstudent == (students[i])
instead use theequals
method.