Java HashMap 集合 三种常用遍历

栏目: Java · 发布时间: 8年前

内容简介:Java HashMap 集合 三种常用遍历

HashMap  储存结构 : key  -->  value

key : 键值、唯一的

唯一的key   重复的话  覆盖原来的

value: 值

由于HashMap的特殊储存结构,所以不能直接用 迭代器(Iterator) 遍历

第一种 利用 HaspMap.values( ); 取出 其 value 的值 但不能取出key的值

其的到 Collection 集合

//1.声明一个非泛型HashMap集合
HashMap hm = new HashMap();
//2.利用for循环 对hm 集合 给值
for(int i=0; i < 10; i++){
hm.put(i,i+"+hm");
}
//3.利用value()  返回 value
Collection ct = hm.values();
//4.利用增强for循环 对其遍历
for(Object obj : ct){
 System.out.print(obj+"\t");
}

第二种 利用其HashMap.keySet( );  取出key键  再HashMap.get( Key ); 取出value的值

.keySet( ) 返回一个Set集合

//1.声明一个非泛型HashMap集合
HashMap hm = new HashMap();
//2.利用for循环 对hm 集合 给值
for(int i=0; i < 10; i++){
hm.put(i,i+"+hm");
}
//利用entrySet( );
Set st = hm.entrySet( );
//利用增强for 遍历Set集合
for(Object obj : st){
//不用 instanceof  
//用entrySet() 获取的一定是 entrySet
//直接 向下转型
Entry entry = (Entry)obj;
//利用Entry自带的getKey( ) 和 getValues()取出对应值 
System.out.println("| Key --> "+entry.getKey()+"|--------|"+"value -->"+entry.getValue()+"|");

}

第三种 利用entrySet( ); 遍历  其返回的是一个Set集合

//3.利用keySet( ) 返回Set集合
Set ks = hm.keySet();
//由于Set是无序 没有下标
//选着用迭代器 Iterator
Iterator it = ks.iterator( );
//用while循环输出结果
while(it.hasNext()){
//it.next()  为Object 
//向下转型  if(a instanceof A)
//int key = (int) it.next();
//System.out.println("Key -->"+key+"\t"+"value -->"+hm.get(key));

//直接转换 Object 类型
Object obj = it.next( );
System.out.println("| Key --> "+key+"|--------|"+"value --> "+hm.get(key)+"|");

}

以上都是自己在学 Java 时的笔记

发个博客 纪念点滴

如有雷同,不如加个联系呗


以上所述就是小编给大家介绍的《Java HashMap 集合 三种常用遍历》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Transcending CSS

Transcending CSS

Andy Clarke、Molly E. Holzschlag / New Riders / November 15, 2006 / $49.99

As the Web evolves to incorporate new standards and the latest browsers offer new possibilities for creative design, the art of creating Web sites is also changing. Few Web designers are experienced p......一起来看看 《Transcending CSS》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

SHA 加密
SHA 加密

SHA 加密工具