Collections.binarySearch 的困难 [英] Difficulty with Collections.binarySearch

查看:30
本文介绍了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天全站免登陆