简体   繁体   中英

how to keep a treemap sorted after adding key-values

I have a treemap which is sorted by a compareTo in the Account class.

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.

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.

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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