Quick question about Hashtable.....

  • Thread starter Thread starter Robin Tucker
  • Start date Start date
R

Robin Tucker

When I create a hashtable hashing on Object-->Item, can I mix "string" and
"integer" as the key types? I have a single thumbnail cache for a database
with (hashed on key) and a file view (hashed on string). So, for example,
when I want to know if the file "xyz.abc" is in the cache, I can write
myTable.ContainsKey ( "xyz.abc" ) or if a given DB key is in the hash I can
write myTable.ContainsKey ( 123 ). Or do the keys all have to be of the
same type?

Also, any disadvantages of using this kind of method?
 
Ok, I satisfied myself that its ok to have strings and integers in the same
hash (not sure how this affects things like performance however):

Dim theintKey As Integer = 1
Dim thestrKey As String = "123"
Dim theString As String = "Value"
Dim theValue As Integer = 123
Dim theHash As New Hashtable

theHash.Add(thestrKey, theString)
theHash.Add(theintKey, theValue)

Debug.WriteLine(CType(theHash(theintKey), Integer))
Debug.WriteLine(CType(theHash(thestrKey), String))
 
Robin,
Although you can use both Integer & String as keys in the same HashTable is
it the "correct" thing to do?

Also are you storing two disparate values by two disparate keys? It appears
that you have intKey storing strValue, while strKey is storing intValue!

I would find it more "correct" to have two HashTables, one keyed by Integer
& one keyed by String, where both store the same value, or each store their
own value. These two HashTables would be encapsulated within a single class.

Something like:

Public Class ThumbnailCache

Private m_ids As HashTable
Private m_names As HashTable

Public Sub Add(id As Integer, name As String, value As Object)
m_ids.Add(id, value)
m_names.Add(name, value)
End Sub

Public Function Contains(id As Integer) as Boolean
Return m_ids.Contains(id)
End Function

Public Function Contains(name As String) As Boolean
Return m_names.Contains(name)
End Function

Default Public Readonly Property Item(id As Integer) as Object
Get
Return m_ids(id)
End Get
End Property

Default Public Readonly Property Item(name As String) as Object
Get
Return m_names(name)
End Get
End Property

End Class

If the two types of key are storing their own type of values I would
considering inheriting each from DictionaryBase.

Hope this helps
Jay
 
Its true in my example, but in my program I have a single NodeBinary class;
one view can load them into the cache from disk and the other from the
database. Therefore, I need to hash the NodeBinary objects with either a
string path or an integer key. I got it to work though, but I just felt
that performance wise, its never a good idea to make all of your variables
"object" and let the system work out their types. At least, it isn't so bad
it can't be used.
 
Back
Top