【java基础:List和HashMap】给单列集合赋id,并放入双列集合

要求:

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);
        }

    }
}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值