Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
            }
        }
    }
like image 206
KLTR Avatar asked Oct 31 '22 12:10

KLTR


1 Answers

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

like image 79
Eran Avatar answered Nov 14 '22 12:11

Eran