我有一個未排序的排序列表和另一個排序順序排列的列表。我需要添加一個刪除按鈕來從原始訂單和排序順序中刪除單詞,但要使用binarySearch刪除我需要對原始訂單進行排序。但我需要保持它未排序...使用binarySearch從ArrayList中刪除單詞
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()));
}
爲什麼你需要使用'的binarySearch '? – chrylis
你只能在有序列表中使用'binarySearch',所以如果你想保持你的列表不被排序,只需使用'list.contains(String)'。 – alicjab
[Burrows-Wheeler Transform](http://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform)涉及可逆排序。但它不會幫助您進行二分查找。 –