// This method removes Song at index from the list and returns it. // it returns
ID: 441049 • Letter: #
Question
// This method removes Song at index from the list and returns it. // it returns null if the index value is out of bounds. // if Song s occurs more than one time on the list, you must remove all // occurrences in the list. public Song removeSong(int index) { if (index < 0) { return null ; } if (songList.get(index) != null) { Song s = songList.get(index) ; for (int i = 0 ; i < songList.size() ; i++) { if ( songList.get(i).equals(s)) { songList.remove(s); } } return s; } return null; } I need help with this. I keep getting out of bound exception. I tried while loop instead of for loop and still not working. Please fixExplanation / Answer
//Rate me first then only I can get points
//We need to decrease i, as when an element removed , size of list changes. The code in read shows the correction
public Song removeSong(int index) { if (index < 0) { return null ; } if (songList.get(index) != null) { Song s = songList.get(index) ; for (int i = 0 ; i < songList.size() ; i++) { if ( songList.get(i).equals(s)) { songList.remove(s); i--;} } return s; } return null; }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.