简体   繁体   中英

Tombstones in hash tables

I am writing a class for a hash table. The hash table is an array of objects from a class I wrote, called HashVariable . The HashVariable has only two properties, a name, and a integer value. I know that if I delete an item from the table I will have to replace it with a 'tombstone' but I'm not sure what I should be using as a tombstone.

I haven't really tried much as I'm not sure what I could do. I could try to cast a character to HashVariable and insert it into the array but I can't cast it like that.

Since the "HashVariable" is a class you have written you can have a boolean variable to mark the HashVariable as tombstone ( apart from having a name and value). For an example implementation take a look here .

There are a number of ways that you could do this, depending on what is allowed to be stored in your table.

  • If your table does not allow for null objects, then you could use a null object to mark a slot that's free, then have the associated integer take on different values based on why the slot is empty (for example, 0 means "was never filled," 1 means "tombstone", etc.)

  • If your table does allow for null objects, you could special-case null as a key and store null separately from the rest of the hash table (say, have dedicated fields of the class corresponding to whether null is a key, and, if so, what value is associated with it). You could then use the above technique to mark empty table slots.

  • If your table does not allow for negative keys, then you could use negative keys to mark empty slots (maybe, for example, -1 means "this slot is empty," and -2 means "this is a tombstone.")

  • If your table allows for arbitrary keys and values, then you could add in parallel arrays of booleans (or an array of integers that works as a bitvector, which is more space-efficient) to mark which slots are empty and which slots are tombstones.

  • If you're okay with a level of indirection, you could have each table slot be a pointer to an object that represents information about the slot. You could have some base class type (say, HashSlot ) with two subclasses (say, Tombstone and Entry ), where Tombstone just marks a tombstone slot and Entry actually stores the key/value pair.

This isn't an exhaustive list of options. As you can tell, there are lot of strategies you could use here! See which of these looks best-suited to your particular setup.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM