Java数组二进制搜索对象与另一个类中的比较器

Kin*_*mph 1 java arrays binary search

我在编程时仍然非常环保,并且遇到了Java中数组上二进制搜索语法的问题.我试图调用存在于从我使用二进制搜索类单独的一类比较方法(重载"比较"方法).本质上我的目标是搜索数组存储在只有一个变量构成数组的对象.没有比较器,我没有成功这样做,因为我创建了一个"虚拟"对象,只保留搜索所需的标准作为密钥.

这是我的二进制搜索代码:

Song searchSong = new Song(artistInput, artistInput, artistInput);
int search = Arrays.binarySearch(songs, searchSong, new compare<Song>());
Run Code Online (Sandbox Code Playgroud)

这是我的重载比较器的代码,同样在一个单独的类中:

public int compare (Song firstSong, Song secondSong) {
  return firstSong.getArtist().compareTo(secondSong.getArtist());
}
Run Code Online (Sandbox Code Playgroud)

我确信这只是一件我想念的简单事,但我还没有找到答案.我感谢任何帮助,如果需要更多细节,请告诉我.我知道二进制搜索的代码不能用它的当前形式.

Jir*_*ser 5

尝试

 Song searchSong = new Song(artistInput, artistInput, artistInput);
 int search = Arrays.binarySearch(songs, searchSong, new Comparator<Song>(){
    @Override
    public int compare(Song s1, Song s2) {
      return s1.getArtist().compareTo(s2.getArtist());
    }
 });
Run Code Online (Sandbox Code Playgroud)

Java 8的更新:

 int search = Arrays.binarySearch(songs, searchSong, 
   (Song s1, Song s2) -> s1.getArtist().compareTo(s2.getArtist()));
Run Code Online (Sandbox Code Playgroud)