上一遍文档讲到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