使Collections.binarySearch()与compareToIgnoreCase一起使用? [英] Making Collections.binarySearch() work with compareToIgnoreCase?

查看:61
本文介绍了使Collections.binarySearch()与compareToIgnoreCase一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我要在一个巨大的ArrayList中搜索特定的String值,但是如果我要查找的String与String I相等(不区分大小写),我需要Collections.binarySearch()返回> = 0的值传递给binarySearch()方法.

So I am searching a huge ArrayList for a particular String value, but I need Collections.binarySearch() to return a value >=0 if the String I am looking for is equal( non case-sensitive) to the String I pass into the binarySearch() method.

现在,在Collections.binarySearch()的源代码中,它最终将调用以下代码行.

Now in the source code for Collections.binarySearch(), it eventually calls the following lines of code.

 Comparable<? super T> midVal = list.get(mid);
 int cmp = midVal.compareTo(key);

如此看来,我无法覆盖String作为其最终值(因此防止我覆盖其compareTo()方法来调用compareToIgnoreCase()),还有其他方法可以实现吗?

So seen as I cannot override String as its final (therefore preventing me from overriding its compareTo() method to call compareToIgnoreCase() ), is there any other I can achieve this?

任何帮助都将非常感谢.

Any help would be great thanks.

推荐答案

要执行不区分大小写的二进制搜索,请使用 String :: compareToIgnoreCase 作为比较器:

To perform case-insensitive binary search, use String::compareToIgnoreCase as a comparator:

int i = Collections.binarySearch(list, key, String::compareToIgnoreCase);

这将比比较减少为相同大小写的两个字符串更快,因为 compareToIgnoreCase()会一一比较字符,仅在需要时减少字符的大小写,如果字符串是首字符不同.

This will perform faster than comparing two strings reduced to the same case, because compareToIgnoreCase() compares chars one by one, reducing case of chars only if needed, which allows to return fast if strings are different in first chars.

NB:为了使此比较器的 binarySearch()正常工作,必须使用完全相同的比较器对集合进行排序:

NB: To make binarySearch() with this comparator work properly, collection must be sorted using exactly the same comparator:

Collections.sort(list, String::compareToIgnoreCase);

这篇关于使Collections.binarySearch()与compareToIgnoreCase一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆