Java中高效判斷數(shù)組中是否包含某個(gè)元素的幾種方法
如何檢查一個(gè)數(shù)組(無序)是否包含一個(gè)特定的值?這是一個(gè)在Java中經(jīng)常用到的并且非常有用的操作。同時(shí),這個(gè)問題在Stack Overflow中也是一個(gè)非常熱門的問題。在投票比較高的幾個(gè)答案中給出了幾種不同的方法,但是他們的時(shí)間復(fù)雜度也是各不相同的。本文將分析幾種常見用法及其時(shí)間成本。
檢查數(shù)組是否包含某個(gè)值的方法
使用List
public static boolean useList(String[] arr, String targetValue) {
return Arrays.asList(arr).contains(targetValue);
}
使用Set
public static boolean useSet(String[] arr, String targetValue) {
Set<String> set = new HashSet<String>(Arrays.asList(arr));
return set.contains(targetValue);
}
使用循環(huán)判斷
public static boolean useLoop(String[] arr, String targetValue) {
for(String s: arr){
if(s.equals(targetValue))
return true;
}
return false;
}
使用Arrays.binarySearch()
Arrays.binarySearch()方法只能用于有序數(shù)組!??!如果數(shù)組無序的話得到的結(jié)果就會(huì)很奇怪。
查找有序數(shù)組中是否包含某個(gè)值的用法如下:
public static boolean useArraysBinarySearch(String[] arr, String targetValue) {
int a = Arrays.binarySearch(arr, targetValue);
if(a > 0)
return true;
else
return false;
}
時(shí)間復(fù)雜度
下面的代碼可以大概的得出各種方法的時(shí)間成本。基本思想就是從數(shù)組中查找某個(gè)值,數(shù)組的大小分別是5、1k、10k。這種方法得到的結(jié)果可能并不精確,但是是最簡(jiǎn)單清晰的方式。
public static void main(String[] args) {
String[] arr = new String[] { "CD", "BC", "EF", "DE", "AB"};
//use list
long startTime = System.nanoTime();
for (int i = 0; i < 100000; i++) {
useList(arr, "A");
}
long endTime = System.nanoTime();
long duration = endTime - startTime;
System.out.println("useList: " + duration / 1000000);
//use set
startTime = System.nanoTime();
for (int i = 0; i < 100000; i++) {
useSet(arr, "A");
}
endTime = System.nanoTime();
duration = endTime - startTime;
System.out.println("useSet: " + duration / 1000000);
//use loop
startTime = System.nanoTime();
for (int i = 0; i < 100000; i++) {
useLoop(arr, "A");
}
endTime = System.nanoTime();
duration = endTime - startTime;
System.out.println("useLoop: " + duration / 1000000);
//use Arrays.binarySearch()
startTime = System.nanoTime();
for (int i = 0; i < 100000; i++) {
useArraysBinarySearch(arr, "A");
}
endTime = System.nanoTime();
duration = endTime - startTime;
System.out.println("useArrayBinary: " + duration / 1000000);
}
運(yùn)行結(jié)果:
useList: 13
useSet: 72
useLoop: 5
useArraysBinarySearch: 9
使用一個(gè)長(zhǎng)度為1k的數(shù)組
String[] arr = new String[1000];
Random s = new Random();
for(int i=0; i< 1000; i++){
arr[i] = String.valueOf(s.nextInt());
}
結(jié)果:
useList: 112
useSet: 2055
useLoop: 99
useArrayBinary: 12
使用一個(gè)長(zhǎng)度為10k的數(shù)組
String[] arr = new String[10000];
Random s = new Random();
for(int i=0; i< 10000; i++){
arr[i] = String.valueOf(s.nextInt());
}
結(jié)果:
useList: 1590
useSet: 23819
useLoop: 1526
useArrayBinary: 12
總結(jié)
顯然,使用一個(gè)簡(jiǎn)單的循環(huán)方法比使用任何集合都更加高效。許多開發(fā)人員為了方便,都使用第一種方法,但是他的效率也相對(duì)較低。因?yàn)閷?shù)組壓入Collection類型中,首先要將數(shù)組元素遍歷一遍,然后再使用集合類做其他操作。
如果使用Arrays.binarySearch()方法,數(shù)組必須是已排序的。由于上面的數(shù)組并沒有進(jìn)行排序,所以該方法不可使用。
實(shí)際上,如果你需要借助數(shù)組或者集合類高效地檢查數(shù)組中是否包含特定值,一個(gè)已排序的列表或樹可以做到時(shí)間復(fù)雜度為O(log(n)),hashset可以達(dá)到O(1)。
(英文原文結(jié)束,以下是譯者注)
補(bǔ)充
使用ArrayUtils
除了以上幾種以外,Apache Commons類庫中還提供了一個(gè)ArrayUtils類,可以使用其contains方法判斷數(shù)組和值的關(guān)系。
import org.apache.commons.lang3.ArrayUtils;
public static boolean useArrayUtils(String[] arr, String targetValue) {
return ArrayUtils.contains(arr,targetValue);
}
同樣使用以上幾種長(zhǎng)度的數(shù)組進(jìn)行測(cè)試,得出的結(jié)果是該方法的效率介于使用集合和使用循環(huán)判斷之間(有的時(shí)候結(jié)果甚至比使用循環(huán)要理想)。
useList: 323
useSet: 3028
useLoop: 141
useArrayBinary: 12
useArrayUtils: 181
-------
useList: 3703
useSet: 35183
useLoop: 3218
useArrayBinary: 14
useArrayUtils: 3125
其實(shí),如果查看ArrayUtils.contains的源碼可以發(fā)現(xiàn),他判斷一個(gè)元素是否包含在數(shù)組中其實(shí)也是使用循環(huán)判斷的方式。
部分代碼如下:
if(array == null) {
return -1;
} else {
if(startIndex < 0) {
startIndex = 0;
}
int i;
if(objectToFind == null) {
for(i = startIndex; i < array.length; ++i) {
if(array[i] == null) {
return i;
}
}
} else if(array.getClass().getComponentType().isInstance(objectToFind)) {
for(i = startIndex; i < array.length; ++i) {
if(objectToFind.equals(array[i])) {
return i;
}
}
}
return -1;
}
所以,相比較之下,我更傾向于使用ArrayUtils工具類來進(jìn)行一些合數(shù)祖相關(guān)的操作。畢竟他可以讓我少寫很多代碼(因?yàn)樽约簩懘a難免有Bug,畢竟apache提供的開源工具類庫都是經(jīng)過無數(shù)開發(fā)者考驗(yàn)過的),而且,效率上也并不低太多。
完整測(cè)試代碼
顯然,使用一個(gè)簡(jiǎn)單的循環(huán)方法比使用任何集合都更加高效。許多開發(fā)人員為了方便,都使用第一種方法,但是他的效率也相對(duì)較低。因?yàn)閷?shù)組壓入Collection類型中,首先要將數(shù)組元素遍歷一遍,然后再使用集合類做其他操作。
package zaLearnpackage;
import org.apache.commons.lang3.ArrayUtils;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
//檢查數(shù)組是否包含某個(gè)值的方法
public class TestArray {
//使用List
public static boolean useList(String[] arr,String targetValue){
return Arrays.asList(arr).contains(targetValue);
}
//使用Set
public static boolean useSet(String[] arr,String targetValue){
Set<String> set=new HashSet<String>(Arrays.asList(arr));
return set.contains(targetValue);
}
//使用循環(huán)判斷
public static boolean useLoop(String[] arr,String targetValue){
for(String s:arr){
if(s.equals(targetValue))
return true;
}
return false;
}
//查找有序數(shù)組中是否包含某個(gè)值的用法
public static boolean useArraysBinarySearch(String[] arr,String targetValue){
int a=Arrays.binarySearch(arr, targetValue);
if(a>0)
return true;
else
return false;
}
//使用ArrayUtils
public static boolean useArrayUtils(String[] arr,String targetValue){
return ArrayUtils.contains(arr,targetValue);
}
public static void main(String[] args) {
String[] arr=new String[]{"CD","BC","EF","DE","AB","JK"};
//use list
long startTime=System.nanoTime();
for(int i=0;i<100000;i++){
useList(arr, "A");
}
long endTime=System.nanoTime();
long duration=endTime-startTime;
System.out.println("useList:"+duration/1000000);
//use set
long startTime2=System.nanoTime();
for(int i=0;i<100000;i++){
useSet(arr, "A");
}
long endTime2=System.nanoTime();
long duration2=endTime2-startTime2;
System.out.println("useSet:"+duration/1000000);
//use loop
long startTime3=System.nanoTime();
for(int i=0;i<100000;i++){
useLoop(arr, "A");
}
long endTime3=System.nanoTime();
long duration3=endTime3-startTime3;
System.out.println("useLoop:"+duration/1000000);
//use Arrays.binarySearch()
long startTime4=System.nanoTime();
for(int i=0;i<100000;i++){
useArraysBinarySearch(arr, "A");
}
long endTime4=System.nanoTime();
long duration4=endTime4-startTime4;
System.out.println("useArraysBinarySearch:"+duration/1000000);
}
}
/*
* 顯然,使用一個(gè)簡(jiǎn)單的循環(huán)方法比使用任何集合都更加高效。許多開發(fā)人員為了方便,都使用第一種方法,但是他的效率也相對(duì)較低。因?yàn)閷?shù)組壓入Collection類型中,首先要將數(shù)組元素遍歷一遍,然后再使用集合類做其他操作。
*/
長(zhǎng)字符串?dāng)?shù)據(jù)
遇到一些有規(guī)律的長(zhǎng)字符串?dāng)?shù)據(jù)的解決辦法(找到是否存在要查找的元素,非遍歷)
String inputStrs = "北京,天津,上海,四川,湖南,廣州,深圳,海南";
String[] strList = inputStrs.split(",");
String target = "上海";//1
String result = Arrays.asList(strList).contains(target) ? "查到咯!" : "沒這個(gè)城市啊...";
//2Set<String> set = new HashSet<>(Arrays.asList(strList));
System.out.println(set.contains(target)); // true
System.out.println(result); // result="查到咯!"-----------
到此這篇關(guān)于Java中高效判斷數(shù)組中是否包含某個(gè)元素的幾種方法的文章就介紹到這了,更多相關(guān)Java包含某個(gè)元素判斷內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Mybatis-Plus實(shí)現(xiàn)自定義SQL具體方法
Mybatis-Plus是Mybatis的一個(gè)增強(qiáng)工具,它可以優(yōu)化我們的開發(fā)效率,這篇文章主要介紹了Mybatis-Plus實(shí)現(xiàn)自定義SQL,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-08-08
逆轉(zhuǎn)交替合并兩個(gè)鏈表的解析與實(shí)現(xiàn)
本篇文章主要介紹了將兩個(gè)鏈表逆轉(zhuǎn)交替合并的實(shí)現(xiàn)思路與方法,需要的朋友可以參考下2015-07-07
SpringBoot安全認(rèn)證Security的實(shí)現(xiàn)方法
這篇文章主要介紹了SpringBoot安全認(rèn)證Security的實(shí)現(xiàn)方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-05-05
Java并發(fā)之synchronized實(shí)現(xiàn)原理深入理解
這篇文章主要介紹了Java中synchronized實(shí)現(xiàn)原理詳解,涉及synchronized實(shí)現(xiàn)同步的基礎(chǔ),Java對(duì)象頭,Monitor,Mark Word,鎖優(yōu)化,自旋鎖等相關(guān)內(nèi)容,具有一定借鑒價(jià)值,需要的朋友可以參考下2021-08-08
詳解Spring Boot中使用AOP統(tǒng)一處理Web請(qǐng)求日志
本篇文章主要介紹了詳解Spring Boot中使用AOP統(tǒng)一處理Web請(qǐng)求日志,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05
JAVA通過HttpClient發(fā)送HTTP請(qǐng)求的方法示例
本篇文章主要介紹了JAVA通過HttpClient發(fā)送HTTP請(qǐng)求的方法示例,詳細(xì)的介紹了HttpClient使用,具有一定的參考價(jià)值,有興趣的可以了解一下2017-09-09

