栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 forde(List list)
	{
		ArrayList alist=new ArrayList<>();
		for (peo p : list) {
			if(p.name.contains("hero-5555"))
			alist.add(p);
		}
		return alist;
	}
	public HashMap hash(List hs)
	{
		HashMap 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 sd=new ArrayList<>();
      HashMap 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 > 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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/353723.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号