java practice HashMap性能比较与普通循环遍历

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值