简体   繁体   English

如何在添加键值后对树图进行排序

[英]how to keep a treemap sorted after adding key-values

I have a treemap which is sorted by a compareTo in the Account class. 我有一个树图,它按Account类中的compareTo排序。

When I initate the treemap, it is sorted but when I try use this function (to add money to a specific account), it works only if the values I change are not the first or last in the treemap. 当我启动树形图时,它会被排序,但是当我尝试使用此功能(为特定帐户添加资金)时,仅当我更改的值不是树形图中的第一个或最后一个时,它才有效。

Here is the code. 这是代码。 What am I doing wrong? 我究竟做错了什么?

 public static void deposit(TreeMap<Account,MyLinkedList<Customer>> map){
            boolean flag = false;
            int num ;
            int amount;
            System.out.println("please enter account number");
            num = s.nextInt();
            //for(Iterator<Account> i = map.;i.hasNext())
            for(Map.Entry<Account, MyLinkedList <Customer>> entry : map.entrySet()){
                if(entry.getKey().getAccNumber() == num){
                    flag = true;
                    System.out.println("Please enter amount");
                    amount = s.nextInt();
                    entry.getKey().setAccBalance(entry.getKey().getAccBalance()+amount);

                    Account temp = entry.getKey();
                    MyLinkedList<Customer> tempList = entry.getValue();
                    map.remove(entry.getKey());
                    map.put(temp, tempList);

                    break;
                }
            }
            if(flag == false) {
                System.out.println("Account doesn't exist");
                return;
            }
        }
    }

If you have to iterate over the entire Map in order to find an Account with a specific number, you defeat the purpose of using a Map. 如果您必须遍历整个Map以查找具有特定编号的帐户,那么您将无法使用Map。

Perhaps you should have two Maps. 也许你应该有两张地图。 The additional map will be a HashMap<Integer,Account> and will let you locate an Account by account number in constant time. 附加地图将是HashMap<Integer,Account> ,并允许您按固定时间按帐号查找Account

This will allow you to get rid of the loop (since once you have the Account for the given account number, a single map.get(account) will get you the corresponding value. This will allow you to remove and add entries from/to the existing TreeMap , which you can't do while iterating over the entry set (well, you could do removal using an explicit iterator over the entry set, but not insertion). 这将让你摆脱循环的(因为一旦你的Account的指定帐户数量,单个map.get(account) ,会得到相应的价值。这将允许您删除和/添加条目现有的TreeMap ,在迭代条目集时你不能做(好吧,你可以在条目集上使用显式迭代器进行删除,但不能插入)。

BTW, unless your TreeMap 's compareTo uses the account balance to determine the ordering, you don't have to remove the entry from the TreeMap and re-add it with the updated balance. 顺便说一句,除非您的TreeMapcompareTo使用帐户余额来确定排序,否则您不必从TreeMap中删除该条目并使用更新的余额重新添加它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM