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. Asp.Net中的获取Web.config中设置的参数!(前后台的代码示例)

    一.Web.config中设置代码     <appSettings>         <add key="deleted" value="1" ...

  2. <转>浅谈DNS体系结构:DNS系列之一

    浅谈DNS体系结构 DNS是目前互联网上最不可或缺的服务器之一,每天我们在互联网上冲浪都需要DNS的帮助.DNS服务器能够为我们解析域名,定位电子邮件服务器,找到域中的域控制器……面对这么一个重要的服 ...

  3. 【原】Storm序列化

    5. Storm高级篇 序列化 Dynamic typing Custom serialization Java serialization Component-specific serializat ...

  4. 数据库连接类oracleHelper

    //=============================================================================== // OracleHelper ba ...

  5. bzoj 4448 [Scoi2015]情报传递(主席树,LCA)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=4448 [题意] 给定一颗树,询问一条路径上权值小于t-c的点数. [思路] 将一个2查 ...

  6. Java transient、Volatile关键字

    Volatile修饰的成员变量在每次被线程访问时,都强迫从主内存中重读该成员变量的值.而且,当成员变量发生变化时,强迫线程将变化值回写到主内存.这样在任何时刻,两个不同的线程总是看到某个成员变量的同一 ...

  7. Contest 7.23(不知道算什么)

    Problem A   URAL 1181 Cutting a Painted Polygon 题目大意就是说有一个N边形,让你做N-3条边,让他们的每个三角形的三个顶点颜色都不相同. 这里有一个引理 ...

  8. 怎么删除windows中无用的服务

    搜索cmd->以管理员身份打开 输入sc delete  服务名 回车即可

  9. Vue2.0表单校验组件vee-validate的使用

    vee-validate使用教程 *本文适合有一定Vue2.0基础的同学参考,根据项目的实际情况来使用,关于Vue的使用不做多余解释.本人也是一边学习一边使用,如果错误之处敬请批评指出* 一.安装 n ...

  10. jquery对象和javascript对象相互转换

    本文转载:http://jeiofw.blog.51cto.com/3319919/786506 jQuery 对象是通过 jQuery 包装DOM 对象后产生的对象.jQuery 对象是 jQuer ...