准备一个ArrayList其中存放3000000(三百万个)Hero对象,其名称是随机的,格式是hero-[4位随机数]
hero-3229
hero-6232
hero-9365
...
因为总数很大,所以几乎每种都有重复,把名字叫做 hero-5555的所有对象找出来
要求使用两种办法来寻找
1. 不使用HashMap,直接使用for循环找出来,并统计花费的时间
2. 借助HashMap,找出结果,并统计花费的时间
1 package Collection; 2 3 import java.util.ArrayList; 4 import java.util.HashMap; 5 6 import charactor.Hero; 7 8 public class HashTest { 9 10 public static void main(String[] args) { 11 ArrayList<Hero> heros = new ArrayList<Hero>(); 12 HashMap<String, ArrayList<Hero>> hashHeros = new HashMap<>(); //key:String便于直接定位"hero-5555",value:ArrayList<Hero>记录key值重复的英雄 13 int n = 3000000; 14 15 for (int i = 0; i < n; i++) { 16 Hero h = new Hero("hero-" + (Math.round(Math.random() * 9000) + 1000)); 17 heros.add(h); 18 19 ArrayList <Hero>tmpArr=new ArrayList<>(); 20 tmpArr.add(h); 21 if(hashHeros.get(h.name) != null){ //key值若重复,不加入hashMap,但是在其key对应的value 里(tmpArr<Hero>)记录下这个英雄 22 hashHeros.get(h.name).add(h); 23 }else{ 24 hashHeros.put(h.name, tmpArr); 25 } 26 } 27 // System.out.println(heros); 28 long st1 = System.currentTimeMillis(); 29 int cnt1 = 0; //记录for循环找到的hero-5555的英雄个数 30 for (int i = 0; i < n; i++) { 31 if (heros.get(i).name.equals("hero-5555")) { 32 cnt1++; 33 } 34 35 } 36 long et1 = System.currentTimeMillis(); 37 System.out.println("for循环共耗时:" + (et1 - st1) + " ms"); 38 System.out.println("一共找到" + cnt1 + "个"); 39 40 long st2 = System.currentTimeMillis(); 41 ArrayList<Hero> tmpArr=hashHeros.get("hero-5555"); 42 long et2 = System.currentTimeMillis(); 43 44 System.out.println("hashMap共耗时:" + (et2 - st2) + " ms"); 45 System.out.println("一共找到" + tmpArr.size() + "个"); 46 47 } 48 }
效果图:
可以明显看到HaspMap的速度优势~
原文:https://www.cnblogs.com/gilgamesh-hjb/p/12220884.html