Cote Mounyo
Cote Mounyo

Reputation: 13965

TreeMap remove not working

I have a TreeMap with a number of entries.

TreeMap<Long, List<Payment>> myPaymentsForYear;

To remove the first week from the Map, I do

 private void removeDaysFromPast() {
    for (int i = 0; i < WEEK; i++) {
        long key = myPaymentsForYear().firstKey();
        myPaymentsForYear.remove(key);
    }
    System.out.println( "date: " + new Date(myPaymentsForYear.firstKey()).toString());
}

However, the printed statement always shows that the firstKey has not been removed. I fact, non of the seven elements is removed. Does anyone know why?

Upvotes: 0

Views: 1313

Answers (3)

masand
masand

Reputation: 21

would be nice if you could share where the error was?

In my case, I wanted the TreeMap with a long as key to be sorted in reverse order and implemented an according Comparator (which I then passed to the TreeMap in the constructor). But as the simple type "long" cannot be used in a Comparator, I had to use the object type "Long" instead:

public class LongComparatorInverted implements Comparator<Long> {
@Override
public int compare(Long lhs, Long rhs) {
    return (lhs == rhs) ? 0 : (lhs < rhs) ? 1 : -1;
}

Sure, Android Studio shows you a warning on the "==", but painfully I ignored it... With the "Long" being an object type, for sure there was no guarantee that I compare the same object when working with the TreeMap.

So the fix for me was - of course - to use equals instead:

return (lhs.equals(rhs)) ? 0 : (lhs < rhs) ? 1 : -1;

Not so easy to find, though...

So if you encounter such an error where "remove" is not working, I´d try to check first whether you use a special Comparator and fully test the Comparator before using it.

Upvotes: 0

Cote Mounyo
Cote Mounyo

Reputation: 13965

The code I have above is completely correct. It turns out the error was entirely somewhere else.

Upvotes: 0

Kyle
Kyle

Reputation: 291

A TreeMap remove statement will always return the object if it's successful, or a null if the key doesn't exist (given that null is an invalid key), or throw an exception. see reference . Have you verified through debugging that you are actually attempting to remove a key that exists and that your remove statement is executing?

Upvotes: 1

Related Questions