I got an assignment to make a register for a class of CD's (String artist, String Title), and one of the necessities in the assignment was to change the order of the shown elements to go by title instead of by artists (alphabetically). When i try to use the code below however i get duplicates of some Strings. Is there anyone who could help me? :P
private ArrayList<CD> reg;
String showSortedTitles() {
String sortedTitles;
StringBuilder sb = new StringBuilder();
ArrayList<CD> temp = new ArrayList<CD>();
temp.add(reg.get(0));
for (int i = 1; i < reg.size(); i++) {
String beftitle = temp.get(i - 1).getTitle();
String newTitle = reg.get(i).getTitle();
if ((newTitle.compareTo(beftitle) < 0)) {
for (int k = 0; k < temp.size(); k++) {
if (newTitle.equals(temp.get(k).getTitle())) {
temp.remove(k);
}
if (newTitle.compareTo(temp.get(k).getTitle()) < 0) {
temp.add(k, reg.get(i));
break;
} else {
temp.add(reg.get(i));
}
}
}
}
for (int i = 0; i < temp.size(); i++) {
CD cd = temp.get(i);
sb.append(cd.getArtist() + (char) ' ' + (char) '-' + (char) ' ' + cd.getTitle() + (char) '\n');
}
sortedTitles = sb.toString();
return sortedTitles;
}