HashMap 寻找是键对应值 依靠泛型 可以用多种类类型 进行定义
代码示例:
package test;
import java.util.HashMap;
import java.util.Iterator;
import le.peo;
import java.util.ArrayList;
import java.util.List;
public class Link {
public List<peo> forde(List<peo> list)
{
ArrayList<peo> alist=new ArrayList<>();
for (peo p : list) {
if(p.name.contains("hero-5555"))
alist.add(p);
}
return alist;
}
public HashMap<Integer, peo> hash(List<peo> hs)
{
HashMap<Integer, peo> sd=new HashMap<>();
for (peo peo : hs) {
if(peo.name.contains("hero-5555"))
{
sd.put(hs.indexOf(peo),new peo("hero-5555"));
}
}
return sd;
}
public static void main(String[] args) {
Link link=new Link();
ArrayList<peo> sd=new ArrayList<>();
HashMap<String,peo> hash=new HashMap<>();
for (int i = 0; i < 30000; i++) {
int h=(int)(Math.random()*10000);
sd.add(new peo("hero-"+h));
}
System.out.println(sd);
long start=System.currentTimeMillis();
System.out.println(link.forde(sd));
long end=System.currentTimeMillis();
System.out.println("for循环寻找:"+(end-start));
long start1=System.currentTimeMillis();
System.out.println(link.hash(sd));
long end1=System.currentTimeMillis();
System.out.println("HashMap寻找:"+(end1-start1));
}
}
代码简单易懂。
Hash Map <>不是单独只能放 String 或者自定义的类型名称
可以如下:
HashMap<String,ArrayList < Hero > > hashMap = new HashMap<>();
这样定义的 意图:
用HashMap储存,此处表示在名字为String的键下存储一个英雄的泛型数组
//即所有名字为String的对象都被储存在当前键下的泛型数组中
至于HashMap中的get 和 put 函数 只要传入的参数的数据类型符合其函数定义的 就可以进行调用
if(hashMap.get(h.name) != null) {
hashMap.get(h.name).add(h);
}
hashMap.get(h.name).add(h);这一个写法就是泛型定义的用处体现
h.name数据类型为String