/*
要求完善设计,使得该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 和余额。
*/
import java.util.*;
class Account {
private long id;
private double balance;
private String password;
Random rd = new Random();
Account(double balance, String password) {
this.balance = balance;
this.password = password;
boolean flag = true;
Random rd = new Random();
while (flag) {
if ((id = rd.nextLong()) > 0) {
flag = false;
}
}
}
public double getBalance() {
return balance;
}
public void setId(long id) {
this.id= id;
}
public long getId() {
return id;
}
}
public class D1 {
public static void main(String args[]) {
long temp;
Map<Long, Account> map = new HashMap<Long, Account>();
List<Account> list = new ArrayList<Account>();
list.add(new Account(10.00, "1234"));
list.add(new Account(15.00, "5678"));
list.add(new Account(0, "1010"));
Account[] acc = (Account[]) list.toArray(new Account[0]);
for (int i = 0; i < acc.length; i++) {
map.put(acc[i].getId(), acc[i]);
}
Set<Long> set = map.keySet();
Iterator<Long> it = set.iterator();
while (it.hasNext()) {
temp = it.next();
System.out.println("id: " + temp + " balance:"
+ map.get(temp).getBalance());
}
}
}
要求完善设计,使得该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 和余额。
*/
import java.util.*;
class Account {
private long id;
private double balance;
private String password;
Random rd = new Random();
Account(double balance, String password) {
this.balance = balance;
this.password = password;
boolean flag = true;
Random rd = new Random();
while (flag) {
if ((id = rd.nextLong()) > 0) {
flag = false;
}
}
}
public double getBalance() {
return balance;
}
public void setId(long id) {
this.id= id;
}
public long getId() {
return id;
}
}
public class D1 {
public static void main(String args[]) {
long temp;
Map<Long, Account> map = new HashMap<Long, Account>();
List<Account> list = new ArrayList<Account>();
list.add(new Account(10.00, "1234"));
list.add(new Account(15.00, "5678"));
list.add(new Account(0, "1010"));
Account[] acc = (Account[]) list.toArray(new Account[0]);
for (int i = 0; i < acc.length; i++) {
map.put(acc[i].getId(), acc[i]);
}
Set<Long> set = map.keySet();
Iterator<Long> it = set.iterator();
while (it.hasNext()) {
temp = it.next();
System.out.println("id: " + temp + " balance:"
+ map.get(temp).getBalance());
}
}
}