mgrstnr
mgrstnr

Reputation: 520

Reorder TreeMap after remove()

I have a treeMap that contains guestbookEntries. The keys are used for ordering and pagination. I have the problem that when I delete an entry, the size() of the guestbookEntries decreases, which results in posts being overwritten for example because I am creating new entries with a key of guestbookEntries.size() + 1.

In order to change this I would like to reorder my TreeMap so that when I remove a key-value-pair. The number of all the following keys is decreased by one, so there should be no "gap" within the TreeMap resulting in guestbookEntries.size() being correct again.

I was thinking of something like that, where postNumber is the key of the entry that was removed.

for(int i = postNumber; i < guestbookEntries.size(); i++) {
            Guestbook gb = guestbookEntries.get(i + 1);
            guestbookEntries.put(postNumber, gb);
            guestbookEntries.remove(postNumber + 1);
}

Is there an easier way of doing that?

Upvotes: 0

Views: 264

Answers (1)

Andremoniy
Andremoniy

Reputation: 34900

I think, that this solution is actually very bad idea. Imagine that you would like to create numbering of posts in your guest book. Somebody else would like to reference to that posts by its id. But when you are shifting your posts back, decreasing theirs ids you doing probably problems for that person, who wants reference posts.

Furthermore, imagine, that somebody deletes post #0, and there are already 100,000 posts in your guestbook. Your program then will have to shift 99,999 post objects in your tree map, decreasing their numbers.

The only possible good solution in this case, do not use guestbookEntries.size() + 1 as basis for generating new post's id.

Instead of this just create some static integer field, it will be good solution to use some concurrent-ready class, for example AtomicInteger.

static AtomicInteger postIdGenerator = new AtomicInteger(0);

The only thing which you will have to do for resolving id for new post, is: postIdGenerator.incrementAndGet().

Upvotes: 1

Related Questions