Collections.binarySearch难度大 [英] Difficulty with Collections.binarySearch

查看:215
本文介绍了Collections.binarySearch难度大的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JAVA和Netbeans的新手,这就是我要做的事情:

用户可以在输入框中写一个CD标题,然后按下删除按钮从列表中删除CD 。如果集合中不存在CD,则可以在发件箱中显示消息以说明此情况。我必须使用 Collections.binarySearch()来执行此操作。这只是整个计划的一部分,但我已经弄明白了其余部分。这就是我所做的:

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);

我遇到的问题是,如果我添加自己的歌曲然后按删除它可以工作但是如果我试图删除arraylist中的任何歌曲它不起作用。非常感谢任何帮助,并提前感谢您!

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!

推荐答案

您的代码始终会删除列表中的最后一首歌曲。这就是为什么它适用您添加的歌曲。它没有使用搜索结果。

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);
}

请记住,阅读API文档并了解方法的作用,而不是您的方法认为它确实如此。

Remember, read the API doc and understand what a method does, not what you think it does.

这篇关于Collections.binarySearch难度大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆