19 每次ID自动加1

/*
 要求完善设计,使得该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 static long id;
    private double balance;
    private String password;
    private long nowId;
    Random rd = new Random();

    Account(double balance, String password) {

        this.balance = balance;
        this.password = password;
    
        setId(id);
        nowId = getId();
    }

    public double getBalance() {
        return balance;

    }

    public void setId(long id) {

        this.id = id + 1;

    }

    public long getNowId() {

        return nowId;

    }

    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"));
        list.add(new Account(100.0, "9009"));

        Account[] acc = (Account[]) list.toArray(new Account[0]);
        for (int i = 0; i < acc.length; i++) {
            map.put(acc[i].getNowId(), 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());

        }

    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值