Map.Entry 遍历之泛型
来源:互联网 发布:mac mini 电源线 编辑:程序博客网 时间:2024/05/21 00:00
上一遍文档讲到Map.Entry的遍历map方法,但没有使用泛型,导致每次遍历获取元素时要强制转换。下面看一版使用泛型的代码示例
import java.util.*;public class AnswerTo19{public static void main(String args[]){List<Account> list = new ArrayList<Account>(); Map<Long,Account> map=new HashMap<Long,Account>();list.add(new Account(10.00,"1234")); list.add(new Account(15.00,"5678")); list.add(new Account(1000,"1010"));//list容器添加3个Account对象Iterator<Account> itor=list.iterator();//遍历list元素while(itor.hasNext()){Account acc=itor.next();Long ID=acc.getId();map.put(ID,acc);//将遍历的list对象的ID和对象分别加入到MAP map中}Set<Map.Entry<Long,Account>> set=map.entrySet();//获取map的映射关系键值对set集合,类型为 Map.Entry 指明获取对象类型Iterator<Map.Entry<Long,Account>> itor2=set.iterator();//指明遍历的元素的类型while(itor2.hasNext()){Map.Entry<Long,Account> me=(Map.Entry<Long,Account>)itor2.next();//遍历set集合中的元素long Id=me.getKey().longValue();//通过遍历元素的getKey()和getValue()获得键值对的 键和值Account act=me.getValue();//前面已指明类型,此处无需转换double balance=act.getBalance();<span style="font-family: Arial, Helvetica, sans-serif;">//前面已指明类型,此处无需转换</span>System.out.println("ID="+Id+" "+"balance="+balance);}}}class Account{long id;double balance;String password;public Account(double balance,String password){this.id=(long)(Math.random()*100);this.balance=balance;this.password=password;}public long getId(){return id;}public double getBalance(){return balance;}public String getPassword(){return password;}public boolean equals(Object obj){if(obj instanceof Account){Account ao = (Account)obj;return (id==ao.getId())&&(password==ao.getPassword())&&(balance==ao.getBalance());}else return super.equals(obj);}public int hashCode(){return password.hashCode();}}
运行结果:
ID=37 balance=15.0
ID=23 balance=10.0
ID=12 balance=1000.0
0 0
- Map.Entry 遍历之泛型
- MAP、ENTRY、for()遍历
- Map.Entry 遍历map详解
- Map.Entry遍历Map泛型
- java中entry遍历map
- Map.Entry简介、遍历HashMap
- Java基础之Iterator、Map、Map.Entry接口,及其综合利用之Map遍历
- Map.Entry类使用遍历Map集合
- Map的遍历,使用内部接口Entry
- 另一种遍历Map的方式: Map.Entry 和 Map.entrySet()
- 另一种遍历Map的方式: Map.Entry 和 Map.entrySet()
- 另一种遍历Map的方式 Map.Entry 和 Map.entrySet()
- 另一种遍历Map的方式: Map.Entry 和 Map.entrySet()
- 另一种遍历Map的方式: Map.Entry 和 Map.entrySet()
- Map.Entry和map.entrySet()---更好的遍历Map
- Map.Entry 和 Map.entrySet() ,用类遍历hashMap,hashTable
- Map.Entry 和 Map.entrySet() ,用类遍历hashMap,hashTable
- Map.Entry 和 Map.entrySet() ,用类遍历hashMap,hashTable
- Android ActionBar-左上角icon设置
- memcached源码阅读----使用libevent和多线程模型
- 7天学会Maven(第二天——Maven 标准目录结构)
- 【EF】 更新条目时出错。有关详细信息,请参见内部异常。
- centos6.5下LNMP环境中修改配置文件后nginx重启失败的解决方法
- Map.Entry 遍历之泛型
- MongoDB关联关系解析以及java操作关联关系
- mysql 5.6安装成功后如何设置密码?
- 上机笔试题1及程序源码
- 简单的jdbc操作数据库例子,高效率插入数据
- Android中的Shape使用总结
- 多线程——NSThread
- 7天学会Maven(第一天——了解 Maven)
- Roman to Integer