2018/12/24
1)使用一个Map,以老师的名字作为键,以老师教授的课程名作为值,表示上述 课程安排。
2)增加了一位新老师Allen 教JDBC
3) Lucy 改为教CoreJava put方法
4)遍历Map,输出所有的老师及老师教授的课程
5)利用Map,输出所有教JSP 的老师。
public class Practice3_1 {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
map.put("Tom", "CoreJava");
map.put("John", "Oracle");
map.put("Susan", "Oracle");
map.put("Jerry", "JDBC");
map.put("Jim", "Unix");
map.put("Kevin", "Jsp");
map.put("Lucy", "Jsp");
map.put("Allen", "JDBC");
map.put("Lucy", "CoreJava");
Set<Entry<String, String>> entrySet = map.entrySet();
for(Entry<String, String> e:entrySet) {
if(e.getValue().equals("Jsp")) {
String key = e.getKey();
System.out.println(key+" ");
System.out.println();
}
System.out.println(e.getKey()+"\t"+e.getValue());
}
}
}
要求完善设计,使得该Account 对象能够自动分配id(可考虑使用从1970-1-1 0:0:0以来的毫秒数为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 和余额。
public class Pratice3_2 {
public static void main(String[] args) {
List<Account> list = new ArrayList<>();
list.add(new Account(10.00, "1234"));
list.add(new Account(15.00, "5678"));
list.add(new Account(0, "1010"));
HashMap<Long, Account> map = new HashMap<>();
Random y = new Random();
for(int i=0;i<list.size();i++) {
map.put(new Date().getTime()+y.nextInt(10), list.get(i));
}
Set<Entry<Long, Account>> entrySet = map.entrySet();
for(Entry<Long, Account> e:entrySet) {
System.out.println(e.getKey()+"\t"+e.getValue());
}
}
}
class Account{
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;
}
private long id;
private double balance;
public Account() {
super();
}
public String toString() {
return "Account [id=" + id + ", balance=" + balance + ", password=" + password + "]";
}
public Account(double balance, String password) {
super();
Random x = new Random();
this.id = new Date().getTime()+x.nextInt(10);
this.balance = balance;
this.password = password;
}
private String password;
}