Difficulty with Collections.binarySearch

末鹿安然 提交于 2019-12-06 16:26:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!