第五题 (Map)设计Account 对象如下:
private long id;
private double balance;
private String password;
要求完善设计,使得该Account 对象能够自动分配id。 给定一个List 如下:
List list = new ArrayList();
list.add(new Account(10.00, “1234”));
list.add(new Account(15.00, “5678”));
list.add(new Account(0, “1010”));
要求把List 中的内容放到一个Map 中,该Map 的键为id,值为相应的Account 对象。 最后遍历这个Map,打印所有Account 对象的id 和余额。
package com.jihelianxi; import java.util.Random; public class Lianxi5 { private long id;
private double balance;
private String password;
Random ra=new Random(); public Lianxi5(double balance, String password) {
super();
this.id=ra.nextInt(1000000)+1000000;
this.balance = balance;
this.password = password;
} public Lianxi5() {
super();
} @Override
public String toString() {
return "Lianxi5 [balance=" + balance + ", password=" + password + "]";
} public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
} }
测试;
package com.jihelianxi; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; public class Lianxi51 { public static void main(String[] args) { Lianxi5 lx=new Lianxi5(); List<Lianxi5> li=new ArrayList<Lianxi5>(); li.add(new Lianxi5(10.00, "1234"));
li.add(new Lianxi5(15.00, "5678"));
li.add(new Lianxi5(0, "1010")); Map<Long, Lianxi5> ma=new HashMap<>(); for(Lianxi5 l:li)
{
ma.put(l.getId(), l);
} for(Long lo:ma.keySet())
{
System.out.println("id="+lo+" 余额="+ma.get(lo).getBalance());
} } }
结果: