要求:
Account账户对象自动分配id;
给定一个List:
List list = new ArrayList();
List.add(new Account(10.00, "1234"));
List.add(new Account(15.00, "15678"));
List.add(new Account(0, "1010"));
要求把List中的内容放到一个Map中,该Map的键为id,值为相应的Account对象;
最后遍历这个Map,打印所有Account对象的id和余额。
Account.java账户类
public class Account { private long id; private double balance; private String password; //无参构造方法 public Account() { } //含全部参数的构造方法 //鼠标右键generate,选择参数,快速构建 public Account(long id, double balance, String password) { this.id = id; this.balance = balance; this.password = password; } //含两个参数的构造方法 public Account(double balance, String password) { this.balance = balance; this.password = password; } //鼠标右键,toString方法,快速构建 @Override public String toString() { return "Account{" + "id=" + id + ", balance=" + balance + ", password='" + password + '\'' + '}'; } //鼠标右键generate,get/set方法,快速构建 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; } }
Test99.java测试类
import java.util.*; public class Test99 { public static void main(String[] args) { List<Account> list = new ArrayList<Account>(); Collections.addAll(list, //获得当前毫秒数,为id赋值,即获得随机的id new Account(System.currentTimeMillis(),10.00,"1234"), new Account(System.currentTimeMillis()+1,15.00,"5678"), new Account(System.currentTimeMillis()+2,10.00,"1010")); HashMap<Long,Account> map = new HashMap<Long,Account>(); //增强for循环 //遍历单列集合list,把获得的id和余额a,放进双列集合map for (Account a : list){ map.put(a.getId(),a); } Set<Long> keySet = map.keySet(); for (Long k : keySet){ //创建account对象,为account对象赋key值 Account account = map.get(k); System.out.println("key:"+k+"value:"+account); } } }
运行结果: