Java中如何使用Collections类的binarySearch()函数进行二分查找
发布时间:2023-09-28 23:55:58
在Java中,可以使用Collections类的binarySearch()函数进行二分查找。binarySearch()函数是一个静态方法,用于在指定的List中搜索指定的元素。
该函数的语法如下:
public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key)
该函数的参数包括一个要进行查找的List对象和要查找的元素。注意,List对象必须是已经排序的。
binarySearch()函数返回一个int值,表示要查找的元素在List中的索引。如果List中不存在该元素,则返回一个负数,这个负数是可以插入该元素的位置的负数索引。
以下是使用binarySearch()函数进行二分查找的示例代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BinarySearchExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(3);
numbers.add(5);
numbers.add(7);
numbers.add(9);
numbers.add(11);
int index = Collections.binarySearch(numbers, 7);
System.out.println("Index of 7: " + index);
}
}
在上面的代码中,首先创建一个ArrayList对象numbers,并向其中添加了一些元素。然后,在使用binarySearch()函数查找元素7时,会返回它在List中的索引,即2。程序会输出"Index of 7: 2"。
需要注意的是,如果List中存在多个相同的元素,binarySearch()函数无法保证返回的是哪个元素的索引。因此,在使用binarySearch()函数之前,应该先对List进行排序。
另外,还有一个重载的binarySearch()函数,可以通过传入一个Comparator对象来指定元素的比较方式。以下是使用Comparator的示例代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class BinarySearchExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Carol");
names.add("Dave");
names.add("Eve");
Comparator<String> reversedComparator = Collections.reverseOrder();
int index = Collections.binarySearch(names, "Dave", reversedComparator);
System.out.println("Index of 'Dave': " + index);
}
}
在上面的代码中,首先创建一个ArrayList对象names,并向其中添加了一些元素。然后,创建了一个Comparator对象reversedComparator来指定元素的比较方式为倒序。在使用binarySearch()函数查找元素"Dave"时,会按照倒序的方式进行比较,程序会输出"Index of 'Dave': 1"。
