使用Collections.reverseOrder()作为Comparator时,Collections.binarySearch()为何返回-1?
问题分析与解决
为什么返回-1?
Collections.binarySearch() 带比较器的重载版本有个硬性要求:目标集合必须已经按照该比较器的规则完成排序。
你的代码里,集合 al 是按升序添加的([10,20,30,40,50]),但查找时用了 Collections.reverseOrder()(降序比较器)。此时二分查找会按照降序逻辑遍历升序集合,完全匹配不上,自然找不到元素,返回-1。
两种解决办法
方法一:先按指定比较器排序,再查找
先把集合用同一个降序比较器排序,让集合顺序和查找逻辑统一:
package com.core.java.collections; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class CollectionsBinarySearch { public static void main(String[] args) { List<Integer> al = new ArrayList<Integer>(); al.add(10); al.add(20); al.add(30); al.add(40); al.add(50); // 先按降序比较器排序集合 Collections.sort(al, Collections.reverseOrder()); // 再用相同比较器查找 int index = Collections.binarySearch(al, 50, Collections.reverseOrder()); System.out.println("Found at index " + index); // 输出0,排序后50在第一位 } }
方法二:去掉比较器,使用默认升序查找
因为你的集合本身就是升序的,直接用不带比较器的重载版本即可:
package com.core.java.collections; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class CollectionsBinarySearch { public static void main(String[] args) { List<Integer> al = new ArrayList<Integer>(); al.add(10); al.add(20); al.add(30); al.add(40); al.add(50); // 用默认升序比较器查找 int index = Collections.binarySearch(al, 50); System.out.println("Found at index " + index); // 输出4,符合预期 } }
内容的提问来源于stack exchange,提问作者Aparna
相关产品推荐
相关产品推荐

