使用binarySearch从ArrayList中删除单词

时间:2014-01-21 15:16:11

标签: java arrays list arraylist

我有一个未分类顺序的arraylist和另一个排序顺序的arraylist。我需要添加一个删除按钮来删除原始订单和排序订单中的单词,但要使用binarySearch删除我需要对原始订单进行排序。但是我需要保持它未分类......

    int songIndex = Collections.binarySearch(song, titleArtistInput.getText());
    int sortedSongIndex = Collections.binarySearch(sortedSong, titleArtistInput.getText());

    //To test the values.
    System.out.println(songIndex + " " + sortedSongIndex);



    if (sortedSongIndex < 0)
    {
        titleArtistOutput.setText("That CD does not exist in the collection, please try again");
    }
    else if (sortedSongIndex >= 0)
    {
        sortedSong.remove(sortedSongIndex);
        Collections.sort(song);
        song.remove(Collections.binarySearch(song, titleArtistInput.getText()));
    }

是否有一种方法可以恢复Collections.sort?或者没有对歌曲ArrayList进行排序的任何方法吗?

编辑: 我让它自己工作!最后。

int sortedSongIndex = Collections.binarySearch(sortedSong, titleArtistInput.getText());

    //if the Collections.binarySearch is negative (song not found), it will output 
    //"That CD does not exist in the collection, please try again", if the sortedSongIndex is positive
    //(the song had been found!) and will remove the indexOf titleArtistInput.getText() from the ArrayLists
    if (sortedSongIndex < 0)
    {
        titleArtistOutput.setText("That CD does not exist in the collection, please try again");
    }
    else if (sortedSongIndex >= 0)
    {
        sortedSong.remove(sortedSong.indexOf(titleArtistInput.getText()));
        song.remove(song.indexOf(titleArtistInput.getText()));

    }

3 个答案:

答案 0 :(得分:4)

使用Map<String, Integer> songToIndexMap存储每首歌曲的索引。

然后就这样做:

Integer index = songToIndexMap.remove(titleArtistInput.getText());
if(index != null) {    // the song has been found!
    song.remove(index);
}

二进制搜索为O(log n),而remove中的get / HashMapO(1)

答案 1 :(得分:0)

我认为,创建对列表是个好主意。一对保持位置,另一对保持价值。 look this question。您仍然可以根据您的价值对列表进行排序。

答案 2 :(得分:0)

如果您想保留原始订单并快速搜索,可以组合Map和ArrayList。

对于每个项目,将其添加到ArrayList,然后将其与列表的索引一起添加到地图中,使用as键作为关键字。

示例:

    ArrayList<Song> originalSort = new ArrayList<>();
    Map<String, Song> theMap = new HashMap<>(); //we will sort by name of song

    //add some items
    Song song = new Song();
    song.author = "thatMan";
    song.name = "someTitle";
    //the index will be the index within the ArrayList
    song.index = originalSort.size();

    originalSort.add(song);
    theMap.put(song.name, song);

    //...

    //iterate with the original order:
    for (Song song : originalSort) {
        System.out.print(song.name);
    }

    //fast search and remove
    song = theMap.remove(song.name);
    originalSort.remove(song.index); //ArrayList has a fast acces by index

如果是出于测试目的,您只需在排序前复制一份清单即可存储原始订单:

List listBackup = originalList.clone(); //remember to use clone method or you will be pointing to the same intance