16

I'm trying to store a set of objects and I need to be able to access them in constant time based on a particular property of the objects. I was hoping to do this by adding the objects to a HashMap and using the property that I want to index by as the key. Is there a HashMap object in VB like in Java, or should I use something else?

Update: Using VB 2010, .NET 4

Cheers

Andrew
  • 161
  • 1
  • 1
  • 4

1 Answers1

23

Depending on your needs you could use a HashTable or a Dictionary.

like this:

Dim dictionary As New Dictionary(Of String, Integer)
dictionary.Add("Dot", 20)
dictionary.Add("Net", 1)
dictionary.Add("Perls", 10)
dictionary.Add("Visual", -1)

Dim Hashtable As New Hashtable()
hashtable.Add("Area", 1000)
hashtable.Add("Perimeter", 55)
hashtable.Add("Mortgage", 540)

Have a look at this and this for more usage examples.

UPDATE:

But, as @Konrad Rudolph says, its better to use a Dictionary for multiple reasons. (On .NET 2.0 and obove)

Thanks for the comment!

Community
  • 1
  • 1
Morvader
  • 2,317
  • 3
  • 31
  • 44
  • 6
    **Never** use `HashTable`, it’s deprecated. `Dictionary` is a complete replacement, is more efficient and type safe. – Konrad Rudolph Mar 09 '11 at 11:32
  • @Konrad asker didn't say what .NET version is being used; it's possible (though unlikely) that it's pre-2.0 – AakashM Mar 09 '11 at 11:48
  • 1
    @AakashM Then the answer should at least reflect this. As it stands, the answer lists them as equal alternatives (and unfortunately the MSDN doesn’t clear this up either). And as you said, this is actually pretty unlikely. – Konrad Rudolph Mar 09 '11 at 11:51
  • Thanks for this. I'm using VB 2010. – Andrew Mar 09 '11 at 12:06