How to check if an array (unsorted) contains a certain value? This is a very useful and frequently used operation in Java. It is also a top voted question on Stack Overflow. As shown in top voted answers, checking if an array contains a certain value can be done in several different ways, but the time complexity could be very different. In the following I will show the time each method takes.

1. 4 Different Ways to Check If an Array Contains a Value

1) Using List:

public static boolean useList(String[] arr, String targetValue) {
return Arrays.asList(arr).contains(targetValue);
}

2) Using Set:

public static boolean useSet(String[] arr, String targetValue) {
Set<String> set = new HashSet<String>(Arrays.asList(arr));
return set.contains(targetValue);
}

3) Using a simple loop:

public static boolean useLoop(String[] arr, String targetValue) {
for(String s: arr){
if(s.equals(targetValue))
return true;
}
return false;
}

4) Using Arrays.binarySearech():

public static boolean useArraysBinarySearch(String[] arr, String targetValue) {
int a = Arrays.binarySearch(arr, targetValue);
if(a > 0)
return true;
else
return false;
}

2. Time Complexity

The approximate time complexity can be compared by using the following code. It is not precise, just search an array of size 5, 1k, 10k, but the idea is clear.

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);
}

Result:

useList:  13
useSet: 72
useLoop: 5
useArraysBinarySearch: 9

Use a larger array (1k):

String[] arr = new String[1000];
 
Random s = new Random();
for(int i=0; i< 1000; i++){
arr[i] = String.valueOf(s.nextInt());
}

Result:

useList:  112
useSet: 2055
useLoop: 99
useArrayBinary: 12

Use a larger array (10k):

String[] arr = new String[10000];
 
Random s = new Random();
for(int i=0; i< 10000; i++){
arr[i] = String.valueOf(s.nextInt());
}

Result:

useList:  1590
useSet: 23819
useLoop: 1526
useArrayBinary: 12

Clearly, using a simple loop method is more efficient than using any collection. A lot of developers use the first method, but it is inefficient. Pushing the array to another Collection type will require spin through all elements to read them in before doing anything with the collection type.

The array must be sorted, if Arrays.binarySearch() method is used. In this case, the array is not sorted, therefore, it should not be used.

Actually, if you really need to check if a value is contained in some array/collection efficiently, a sorted list or tree can do it in O(log(n)) or hashset can do it in O(1).

reference from:http://www.programcreek.com/2014/04/check-if-array-contains-a-value-java/

How to Check if an Array Contains a Value in Java Efficiently?---reference的更多相关文章

  1. [ES2016] Check if an array contains an item using Array.prototype.includes

    We often want to check if an array includes a specific item. It's been common to do this with the Ar ...

  2. leetcode 108 Convert Sorted Array to Binary Search Tree ----- java

    Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 给一 ...

  3. Java反射04 : 通过Array动态创建和访问Java数组

    java.lang.reflect.Array类提供了通过静态方法来动态创建和访问Java数组的操作. 本文转载自:https://blog.csdn.net/hanchao5272/article/ ...

  4. 【LeetCode】453. Minimum Moves to Equal Array Elements 解题报告(Java & Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:模拟过程 方法二:求和-n*最小值 方法三: ...

  5. 【LeetCode】26. Remove Duplicates from Sorted Array 解题报告(Python&C++&Java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 双指针 日期 [LeetCode] https:// ...

  6. Array和String测试与java.String.split

    java.string.split() 存在于java.lang包中,返回值是一个数组. 作用是按指定字符或者正则去切割某个字符串,结果以字符串数组形式返回. 例 String [] toSort = ...

  7. dubbo高级配置学习

    启动时检查 可以通过check="false"关闭检查,比如,测试时,有些服务不关心,或者出现了循环依赖,必须有一方先启动. 关闭某个服务的启动时检查:(没有提供者时报错) < ...

  8. dubbo高级配置学习(上)

    启动时检查 Dubbo缺省会在启动时检查依赖的服务是否可用,不可用时会抛出异常,阻止Spring初始化完成,以便上线时,能及早发现问题,默认check=true. 如果你的Spring容器是懒加载的, ...

  9. Dubbo -- 系统学习 笔记 -- 示例 -- 启动时检查

    示例 想完整的运行起来,请参见:快速启动,这里只列出各种场景的配置方式 启动时检查 Dubbo缺省会在启动时检查依赖的服务是否可用,不可用时会抛出异常,阻止Spring初始化完成,以便上线时,能及早发 ...

随机推荐

  1. OnItemClickListener 的参数详解(转)

    转载地址:http://blog.iamzsx.me/show.html?id=147001 我们在使用ListView的时候,一般都会为ListView添加一个响应事件android.widget. ...

  2. 安装nagios出现的两个错误记录

    最近在安装nagios,出现几个错误记录: 一 检查nagios配置的时候出现错误如下: Warning: Duplicate definition found for host 'kelly' (c ...

  3. 精妙SQL语句 基础

    精妙SQL语句SQL语句先前写的时候,很容易把一些特殊的用法忘记,我特此整理了一下SQL语句操作,方便自己写SQL时方便一点,想贴上来,一起看看,同时希望大家能共同多多提意见,也给我留一些更好的佳句, ...

  4. JSON解析关联类型发生死循环 There is a cycle in the hierarchy!

    解决办法是忽略掉关联类型的数据,使用jsonConfig进行配置,代码如下: JsonConfig jsonConfig = new JsonConfig();  //建立配置文件 jsonConfi ...

  5. Linux cat命令参数及使用方法详解

    cat是Linux系统下用来查看文件连续内容用的指令,字面上的含意是“concatenate”(连续)的缩写.除了用来作为显示文件内容外,cat指令也可用于标准流上的处理,如将显示的信息转入或附加另一 ...

  6. java数字保留两位小数四舍五入

    import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.NumberFormat; public c ...

  7. 转载C#中堆(heap)和栈(stack)的区别

    转载原地址  http://www.cnblogs.com/wangshenhe/archive/2013/02/18/2916275.html [转]C#堆和栈的区别 理解堆与栈对于理解.NET中的 ...

  8. UVa 1252 Twenty Questions (状压DP+记忆化搜索)

    题意:有n件物品,每件物品有m个特征,可以对特征进行询问,询问的结果是得知某个物体是否含有该特征,要把所有的物品区分出来(n个物品的特征都互不相同), 最小需要多少次询问? 析:我们假设心中想的那个物 ...

  9. WinForm开发浏览器,WebBrowser获取页面内容,如何解决中文乱码

    WebBrowser的编码可以从文档对象中获得,将代码改为如下即可. System.IO.StreamReader getReader = new System.IO.StreamReader(thi ...

  10. Thinkphp框架 -- ajax无刷新上传图片

    用Thinkphp框架做无刷新上传图片 视图层 View <!doctype html> <html lang="en"> <head> < ...