How to keep a treemap sorted after adding key values

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

When I run the treemap, it is sorted, but when I try to use this function (to add money to a specific account), it only works if the values ​​that 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; } } } 
+5
source share
1 answer

If you need to iterate over the entire card to find an Account with a specific number, you defeat the purpose of using the Card.

Perhaps you should have two Maps. An additional card will be HashMap<Integer,Account> and will allow you to find Account by account number in a constant time.

This will allow you to get rid of the loop (because as soon as you have an Account for a given account number, one map.get(account) will get you the corresponding value. This will allow you to delete and add entries from / to the existing TreeMap , which you cannot do iterations over the recordset (well, you could do the deletion using an explicit iterator over the recordset, but not insert).

BTW, if your TreeMap compareTo does not use the account balance to determine the order, you do not need to delete the record from TreeMap and re-add it with the updated balance.

+2
source

Source: https://habr.com/ru/post/1239239/


All Articles