当前位置: 首页 > news >正文

四种方法校验数组中是否包含某个指定的字符串

校验数组中是否包含某个指定的字符串这个场景会经常使用到,有一次无意中看到一篇文章,觉得写得挺好,扣出来给大家分享下,先说明下,是从一个老外的网站上弄过来的。

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, this can be done in several different ways, but the time complexity could be very different. In the following I will show the time cost of each method.

 

1. Four 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.binarySearch():
* The code below is wrong, it is listed here for completeness. binarySearch() can ONLY be used on sorted arrays. You will see the result is weird when running the code below.

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 cost can be measured by using the following code. The basic idea is to search an array of size 5, 1k, 10k. The approach may not be precise, but the idea is clear and simple.

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 requires 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).

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

相关文章:

  • 水晶报表数据整形模型 兼答CSDN
  • 微信小程序 事件
  • PHPMYADMIN简明安装教程
  • Linux 系统中这样修复 SambaCry 漏洞
  • (转)Scala的“=”符号简介
  • POJ 1739 Tony's Tour, 连通性状态压缩DP
  • 具体解释Hibernate中的二级缓存
  • JavaScript学习系列(一)什么是javascript
  • 移动端唤起键盘时取消position:fixed定位
  • 磁盘爆满
  • 29、Java并发性和多线程-非阻塞算法
  • 吕佳(帮别人名字作诗)
  • 如何弹出固定大小及内容的网页窗口
  • jvm 各个区含义
  • 文章推荐
  • gf框架之分页模块(五) - 自定义分页
  • HTTP--网络协议分层,http历史(二)
  • mysql外键的使用
  • PV统计优化设计
  • Twitter赢在开放,三年创造奇迹
  • WinRAR存在严重的安全漏洞影响5亿用户
  • 回流、重绘及其优化
  • 区块链技术特点之去中心化特性
  • 蚂蚁金服CTO程立:真正的技术革命才刚刚开始
  • ​iOS安全加固方法及实现
  • ​LeetCode解法汇总518. 零钱兑换 II
  • # include “ “ 和 # include < >两者的区别
  • (C++17) std算法之执行策略 execution
  • (六)库存超卖案例实战——使用mysql分布式锁解决“超卖”问题
  • (强烈推荐)移动端音视频从零到上手(下)
  • (原創) 物件導向與老子思想 (OO)
  • .mysql secret在哪_MYSQL基本操作(上)
  • .net core控制台应用程序初识
  • .NET开源项目介绍及资源推荐:数据持久层 (微软MVP写作)
  • .NET中 MVC 工厂模式浅析
  • .w文件怎么转成html文件,使用pandoc进行Word与Markdown文件转化
  • @RequestMapping-占位符映射
  • @test注解_Spring 自定义注解你了解过吗?
  • [20190401]关于semtimedop函数调用.txt
  • [202209]mysql8.0 双主集群搭建 亲测可用
  • [ABP实战开源项目]---ABP实时服务-通知系统.发布模式
  • [AMQP Connection 127.0.0.1:5672] An unexpected connection driver error occured
  • [BZOJ4337][BJOI2015]树的同构(树的最小表示法)
  • [C/C++] C/C++中数字与字符串之间的转换
  • [C++] cout、wcout无法正常输出中文字符问题的深入调查(1):各种编译器测试
  • [CentOs7]搭建ftp服务器(2)——添加用户
  • [CF543A]/[CF544C]Writing Code
  • [GDOUCTF 2023]<ez_ze> SSTI 过滤数字 大括号{等
  • [hibernate]基本值类型映射之日期类型
  • [IE6 only]关于Flash/Flex,返回数据产生流错误Error #2032的解决方式
  • [JAVA设计模式]第二部分:创建模式
  • [LeetCode] NO. 387 First Unique Character in a String
  • [leetcode]114. Flatten Binary Tree to Linked List由二叉树构建链表
  • [na]wac无线控制器集中转发部署的几种情况
  • [NowCoder]牛客OI周赛3