- 难点
HashMap
的初始化比较难实现 - 初始化实现如下:
HashMap<String,List<Hero>> heroMap =new HashMap<String, List<Hero>>();
for (Hero h : hero) {
List<Hero> list= heroMap.get(h.name);
if(list==null){
list = new ArrayList<>();
heroMap.put(h.name, list);
}
list.add(h);
}
- 首先创建一个
HashMap
对象。key
为名字(例如hero0000-hero9999
)。 - hero本身就是一个
ArrayList
对象,里面存在着由随机数生成的30w
个对象。重点是这30w
个对象里面可能存在着对象不同但名字相同的情况。这时候HashMap
的作用就来了,相当于一个名字存在多个对象,把那些名字相同的对象放到一个List
里面。(生成hero
的代码见下文完整实现) - 进入增强
for
循环进行迭代。首次进入for
循环,创建Hero
的List对象(例如创建了名字为hero-1234
的对象),它的值由HashMap
的value
给出,但是这时候还没有键值对的对应。也就是没有value
,进一步说就是list
不存在(null)
。因此进入step4
。 if
判断的目的是当迭代往后走的时候,如果h.name
的list
不存在,就需要 list = new ArrayList<>();
,然后将名字h.name
和对应list
装进HashMap
对象。- 如果当前
h.name
的list
已经存在,那就将当前的h添加到已有的list中去。
package collection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class HashMapTest {
public static void main(String[] args) {
System.out.println("for循环初始化开始");
List<Hero> hero = new ArrayList<Hero> ();
for(int i = 0; i<300*10000; i++) {
hero.add(new Hero("hero-"+(int)(Math.random()*9999)));
}
System.out.println("for循环初始化结束");
String name = "hero-5555";
int count = 0;
long start1 = System.currentTimeMillis();
for(int i = 0; i<hero.size(); i++) {
Hero h = (Hero)hero.get(i);
if(name.equals(h.name)) {
count++;
}
}
long end1 = System.currentTimeMillis();
System.out.printf("使用for循环一共找到%d个hero-5555\n总花费时间是%d毫秒\n",count,end1-start1);
System.out.println("-------------------------");
System.out.println("HashMap初始化开始");
HashMap<String,List<Hero>> heroMap =new HashMap<String, List<Hero>>();
for (Hero h : hero) {
List<Hero> list= heroMap.get(h.name);
if(list==null){
list = new ArrayList<>();
heroMap.put(h.name, list);
}
list.add(h);
}
System.out.println("HashMap初始化结束");
long start2 = System.currentTimeMillis();
List <Hero> result= heroMap.get("hero-5555");
long end2 = System.currentTimeMillis();
System.out.printf("使用HashMap一共找到%d个hero-5555\n总花费时间是%d毫秒",result.size(),end2-start2);
}
}
- 结果截图