Arrays.binarySearch要求数组必须有序,否则结果不可预测;元素存在时返回索引,不存在时返回(-(插入点)-1),可通过该值获取插入位置;支持基本类型和对象数组,对自定义对象需实现Comparable或传入Comparator以保证排序与查找逻辑一致。

Arrays.binarySearch
要充分利用
Arrays.binarySearch
来看个例子:
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.ArrayList;
public class BinarySearchTips {
public static void main(String[] args) {
int[] sortedArray = {10, 20, 30, 40, 50};
int index = Arrays.binarySearch(sortedArray, 30); // 找到,返回2
System.out.println("Found 30 at index: " + index); // 输出: Found 30 at index: 2
int indexNotFound = Arrays.binarySearch(sortedArray, 35); // 没找到
System.out.println("35 not found, potential insertion point: " + indexNotFound); // 输出: 35 not found, potential insertion point: -4
// 如果数组是无序的,结果会很诡异,千万别这么用!
int[] unsortedArray = {50, 10, 30, 20, 40};
int weirdIndex = Arrays.binarySearch(unsortedArray, 30); // 结果可能是任何值,不可信
System.out.println("Searching 30 in unsorted array (DO NOT DO THIS!): " + weirdIndex); // 输出结果不确定,可能为-1, -3等,但都不是30的实际位置
System.out.println("\n--- Object Array Example ---");
String[] names = {"Alice", "Bob", "Charlie", "David"};
Arrays.sort(names); // 确保有序
int nameIndex = Arrays.binarySearch(names, "Charlie");
System.out.println("Found Charlie at index: " + nameIndex); // 输出: Found Charlie at index: 2
// 使用Comparator进行查找
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));
// 需要先排序,这里按年龄排序
Collections.sort(people, Comparator.comparing(Person::getAge));
// 排序后: [Bob(25), Alice(30), Charlie(35)]
System.out.println("Sorted people by age: " + people);
// binarySearch也需要同样的Comparator
// 注意:传入的key对象,其用于比较的属性需要与Comparator一致
int personIndex = Arrays.binarySearch(people.toArray(new Person[0]), new Person("Unknown", 35), Comparator.comparing(Person::getAge));
System.out.println("Found person with age 35 at index: " + personIndex); // 输出: Found person with age 35 at index: 2
}
// Person class (simplified for demonstration)
static class Person {
String name;
int age;
public Person(String name, int age) { this.name = name; this.age = age; }
public String getName() { return name; }
public int getAge() { return age; }
@Override public String toString() { return name + "(" + age + ")"; }
}
}当元素找到时,它返回的是该元素的索引。如果没找到,它返回的是
(-(插入点) - 1)
(-(-3) - 1) = 2
立即学习“Java免费学习笔记(深入)”;
除了基本类型数组,
Arrays.binarySearch
Comparable
Comparator
binarySearch
key
binarySearch
Arrays.binarySearch
log₂N
举个例子,一个有100万个元素的数组:
log₂1000000
所以,它的适用场景非常明确:
一个常见的误区是,有人觉得“反正数据量不大,无所谓”。但一个好的习惯是,只要条件允许(数据有序),就应该优先考虑二分查找,这是一种“防患于未然”的编程哲学。
Arrays.binarySearch
binarySearch
当
binarySearch
i
i
(-(insertionPoint) - 1)
>= 0
i
-(i + 1)
我们再用代码来强化一下理解:
import java.util.Arrays;
public class BinarySearchNegativeReturn {
public static void main(String[] args) {
int[] data = {10, 20, 30, 50, 60};
// 查找存在的元素
int foundIndex = Arrays.binarySearch(data, 30);
if (foundIndex >= 0) {
System.out.println("元素 30 存在,索引为: " + foundIndex); // 输出: 元素 30 存在,索引为: 2
} else {
System.out.println("元素 30 不存在。");
}
// 查找不存在的元素 40
int notFoundIndex = Arrays.binarySearch(data, 40);
if (notFoundIndex >= 0) {
System.out.println("元素 40 存在,索引为: " + notFoundIndex);
} else {
int insertionPoint = -(notFoundIndex + 1);
System.out.println("元素 40 不存在。如果插入,它应该在索引: " + insertionPoint); // 输出: 元素 40 不存在。如果插入,它应该在索引: 3
// 验证:10, 20, 30, (40), 50, 60 -> 40应该在索引3
}
// 查找比所有元素都小的 5
int lessThanAll = Arrays.binarySearch(data, 5);
int insertionPointLess = -(lessThanAll + 1);
System.out.println("元素 5 不存在。如果插入,它应该在索引: " + insertionPointLess); // 输出: 元素 5 不存在。如果插入,它应该在索引: 0
// 查找比所有元素都大的 70
int greaterThanAll = Arrays.binarySearch(data, 70);
int insertionPointGreater = -(greaterThanAll + 1);
System.out.println("元素 70 不存在。如果插入,它应该在索引: " + insertionPointGreater); // 输出: 元素 70 不存在。如果插入,它应该在索引: 5 (数组长度)
}
}这个插入点的概念在需要维护一个有序集合时非常有用,比如你可能想在不重复添加元素的前提下,将新元素插入到正确的位置,保持数组的有序性。
binarySearch
Comparable
Comparator
当处理对象数组时,
Arrays.binarySearch
Comparable
Comparator
如果你的对象本身就有一个“自然顺序”,比如
String
Integer
Comparable<T>
import java.util.Arrays;
import java.util.Comparator;
class Book implements Comparable<Book> {
String title;
int year;
public Book(String title, int year) {
this.title = title;
this.year = year;
}
@Override
public int compareTo(Book other) {
// 自然顺序:按年份升序,年份相同则按标题字母序
if (this.year != other.year) {
return Integer.compare(this.year, other.year);
}
return this.title.compareTo(other.title);
}
@Override
public String toString() {
return "Book{" + "title='" + title + '\'' + ", year=" + year + '}';
}
}
public class BinarySearchObject {
public static void main(String[] args) {
Book[] books = {以上就是Java中Arrays.binarySearch使用技巧的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号