问题
I am new to JAVA and Netbeans and this is what I have to do:
The user can write a CD title in the input box and then remove the CD from the list by pressing the remove button. If the CD does not exist in the collection, then a message can be displayed in the outbox to state this. I have to use Collections.binarySearch()
to do this. This is only a part of the whole program but I already figured out the rest of it. This is what I have done:
ArrayList <String> songs = new ArrayList();
Collections.addAll(songs, "Metric - Fantasies", "\nBeatles - Abbey Road", "\nPearl Jam - Ten", "\nDoors - Alive", "\nThe Rolling Stones - Gimme Shelter\n");
Collections.sort(songs, String.CASE_INSENSITIVE_ORDER);
Collections.binarySearch(songs,"",String.CASE_INSENSITIVE_ORDER);
String delete=songs.remove(songs.size()-1);
String out="";
String Out = null;
for (int i = 0; i < songs.size(); i++)
Out=out + songs;{
output.setText("Original Order\n**************\n" + Out+delete);
The problem I am having is that the if I add my own song and then press remove it works but if I try to remove any of the songs in arraylist it doesnt work. Any help is greatly appreciated and thank you in advance!
回答1:
Your code always removes the last song in the list. That's why it "works" with the songs you add. It's not using the result of the search.
// binarySearch returns the position of the element in the list
// Or a negative number if not found.
int i = Collections.binarySearch(songs, "metric - fantasies", String.CASE_INSENTITIVE_ORDER);
if (i < 0) {
// Not found, display something
} else {
String deleted = songs.remove(i);
}
Remember, read the API doc and understand what a method does, not what you think it does.
来源:https://stackoverflow.com/questions/40835111/difficulty-with-collections-binarysearch