0

Adding and deleting from array

i have this peace of code i don't understand : adding: public boolean addCourse(String course) { for (int i = 0; i < numCourses; i++) {//i'm checking whether course is in the list if (courses[i].equals(course)) return false; } courses[numCourses] = course;//if not he is added numCourses++; return true; } removing: public boolean removeCourse(String course) {//i don't understand following so if someone could explain line by line, thx boolean found = false; int courseIndex = -1; for (int i = 0; i < numCourses; i++) { if (courses[i].equals(course)) { courseIndex = i; found = true; break; } } if (found) { for (int i = courseIndex; i < numCourses-1; i++) { courses[i] = courses[i+1]; } numCourses--; return true; } else { return false; } }

22nd Aug 2017, 4:05 PM
Yurodivi
1 Respuesta
+ 8
E.g. 1 2 3 4 5 6 7 We want to delete 4, so the program loops until it finds 4. 4 is at index 3. The program will start to loop from index 3 to index array_size - 1, and shift all arrays to the left, "covering" 4. 1 2 3 4 <- 5 <- 6 <- 7 result : 1 2 3 5 6 7
23rd Aug 2017, 1:59 AM
Hatsy Rei
Hatsy Rei - avatar