Map.Entry 遍历之泛型

上一遍文档讲到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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值