For this assignment I need to sort one list and also keep the original list, but when I click the button twice, the original list is also sorted.
String output = "";
String sortedOutput = "";
//ORIGINAL OUTPUT
for (int j = 0; j < song.size(); j++){
output += song.get(j) + "\n";
}
//SORTED OUTPUT
for (int k = 0; k < song.size(); k++){
Collections.sort(song);
sortedOutput += song.get(k) + "\n";
}
titleArtistOutput.setText("Original Order\n" + output + "\nSorted Order\n" + sortedOutput);
Is there anything I can put on the first loop to prevent it from getting sorted?
EDIT:
Thank you Jon Skeet!
I made another arraylist
String output = "";
String sortedOutput = "";
List <String> sortedSongs = new ArrayList <String> (song);
for (int j = 0; j < song.size(); j++){
output += song.get(j) + "\n";
}
for (int k = 0; k < song.size(); k++){
Collections.sort(sortedSongs);
sortedOutput += sortedSongs.get(k) + "\n";
}
titleArtistOutput.setText("Original Order\n" + output + "\nSorted Order\n" + sortedOutput);
Sorry for the easy question, I am new to programming.
I suspect you just want to take a copy of the list, then sort that:
List<Song> sortedSongs = new ArrayList<Song>(song);
Collections.sort(sortedSongs); // Will not affect song
Note that this should be done before your loop, not inside it.
See more on this question at Stackoverflow