1

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;
}
hpopiolkiewicz
  • 3,281
  • 4
  • 24
  • 36
Hazzlarn
  • 11
  • 4
  • 4
    Just use Collections.sort with a Comparator. (Unless it was mentioned explicitly that you are to implement your own sorting algorithm) – wvdz Dec 01 '16 at 14:02
  • http://stackoverflow.com/questions/18441846/how-to-sort-an-arraylist-in-java – fantaghirocco Dec 01 '16 at 14:07

1 Answers1

-1

To fix your code, you could do something like this:

public static List<CD> sortedTitle(List<CD> list) {
    List<CD> newList = list; // "copy your list"
    for (int i = 0; i < newList.size(); i++) {
        for (int j = i + 1; j < newList.size(); j++) {
            //comparing
            if (newList.get(i).getTitle().compareTo(newList.get(j).getTitle()) > 0) {
                //"replace; change position"
                CD temp = newList.get(i);
                newList.set(i, list.get(j));
                newList.set(j, temp);
            }
        }
    }
    //return sorted list
    return newList;
}