cj1098
cj1098

Reputation: 1600

How can I delete an item in a hashtable and have the keys adjust accordingly?

Currently I have a homescreen where the user stores titles of their classes they're taking this semester, and tied to each class is their assignments and flashCards for those classes. When the user long-clicks on one of the items on the homepage, I want to delete the class and all its contents (this includes all flashCards and assignments).

I've stupidly stored my data in hashtables with the keys as integers unfortunately. This has caused some problems when I delete items from the table. The keys are directly correlated to the position on the homescreen, and I can't seem to figure out how to readjust the hashtable when the user deletes something from it.

I've thought about using other data structures such as a arrayList but the problem is that the user could possibly and very likely have only one set of flash cards or only one assignment and it happens to be in the 4th position on the homescreen. This means that I would have to fill the first 3 positions with null first before I could insert the value at the 4th position. I definitely don't think I want that...

Any ideas?

Upvotes: 1

Views: 122

Answers (2)

Mikhail Vladimirov
Mikhail Vladimirov

Reputation: 13890

Just assign unique IDs to all entities such as classes, users and assignments. Use these unique IDs, which may be integers, as keys and in all other places where you need to refer to entities. Do not use sequential order of entity as identifier, because it may change when item is deleted or even when items are reordered.

Upvotes: 0

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

I am afraid that with your current implementation, you will not be able to readjust the numbers in the HashTable. I would suggest you use LinkedList for the items on your screen and store iterators to the elements in that list in the HashTable. This way you will be able to efficiently delete any item.

Upvotes: 1

Related Questions