Java-集合=第五题 (Map)设计Account 对象如下: private long id; private double balance; private String password; 要求完善设计,使得该Account 对象能够自动分配id。 给定一个List 如下: List list = new ArrayList(); list.add(new A

第五题 (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 Test03;

public class Account {
    
        private long id;  
        private double balance;  
        private String password;

    Account(double balance,String password)
    {
        this.balance=balance;
        this.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 Test03;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestAccount {

    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")); 
        
        
        Map<Long,Account> m1 = new HashMap<>();
        m1.put((long) 0, list.get(0));
        m1.put((long) 1, list.get(1));
        m1.put((long) 2, list.get(2));
        
        for(Long k:m1.keySet())                //遍历
        {
            System.out.println(m1.get(k).getBalance());
        }


    }

}

 

posted @ 2016-09-28 00:12  张好好  阅读(3912)  评论(0编辑  收藏  举报