测试
在日常开发中,经常用到某个字段是否存在的遍历,hashmap将key换算成hash值作为数组的索引,速度更快,今天无聊,故写个文章。
for循环遍历查询包含某个字符串的平均耗时为 80 单位时间
hashmap查询包含某个字符串的平均耗时为 35 单位时间
综上,在实际应用中,hashmap是检验是否包含字符串的高效方式之一。
import java.util.ArrayList;
import java.util.HashMap;
public class Test03 {
public static void main(String[] args) {
HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();
stringIntegerHashMap.put("雨JL",1);
stringIntegerHashMap.put("雨lgjlgh",1);
stringIntegerHashMap.put("J",1);
stringIntegerHashMap.put("雨D",1);
stringIntegerHashMap.put("雨G",1);
stringIntegerHashMap.put("雨B",1);
stringIntegerHashMap.put("D雨",1);
stringIntegerHashMap.put("雨H",1);
stringIntegerHashMap.put("雨DG",1);
stringIntegerHashMap.put("雨GHH",1);
stringIntegerHashMap.put("雨F",1);
ArrayList<String> strings= new ArrayList<>();
strings.add("雨JL");
strings.add("雨lgjlgh");
strings.add("J");
strings.add("雨D");
strings.add("雨G");
strings.add("雨B");
strings.add("D雨");
strings.add("雨H");
strings.add("雨DG");
strings.add("雨GHH");
strings.add("雨F");
int flag = 0 ;
long start = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
forMethod(flag, strings , "雨F");
}
long timeComsumed1 = System.currentTimeMillis()-start;
System.out.println(timeComsumed1);
flag = 0;
start = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
hashMapMethod(flag, stringIntegerHashMap , "雨F");
}
long timeComsumed2 = System.currentTimeMillis()-start;
System.out.println(timeComsumed2);
System.out.println(timeComsumed2- timeComsumed1);
}
public static void forMethod (int flag ,ArrayList<String> arrayList, String str){
for (String s : arrayList) {
if(str == s){
flag = 1;
return;
}
}
}
public static void hashMapMethod (int flag , HashMap<String,Integer> map, String str){
if ( map.containsKey(str)){
flag = 1;
return;
}
}
}