Visual Basic Hashtable

In visual basic, Hashtable is useful to store a collection of key/value pairs of different data types and those are organized based on the hash code of the key.

 

Generally, the hashtable object will contain buckets to store elements of the collection. Here, the bucket is a virtual subgroup of elements within the hashtable and each bucket is associated with a hash code, which is generated based on the key of the element.

 

In visual basic, hashtable is same as Dictionary object but the only difference is the Dictionary object is useful to store a key-value pair of same data type elements.

 

When we compared with Dictionary object, the hashtable will provide lower performance because the hashtable elements are of object type so the boxing and unboxing process will occur when we store or retrieve values from hashtable.

Visual Basic HashTable Declaration

In visual basic, the hashtable is a non-generic type of collection so we can store key/value pair elements of different data types and it is provided by System.Collections namespace.

 

As discussed, collection is a class so to define a hashtable, we must need to declare an instance of the hashtable class before we perform any operations like add, delete, etc. like as shown below.

 

Dim htbl As Hashtable  = New Hashtable()

If you observe the above hashtable declaration, we created a new hashtable (hshtbl) with an instance of hashtable class without specifying any size.

Visual Basic HashTable Properties

Following are the some of commonly used properties of hashtable in visual basic programming language.

 

PropertyDescription
Count It is used to get the number of key/value pair elements in hashtable.
IsFixedSize It is used to get a value to indicate that the hashtable has fixed size or not.
IsReadOnly It is used to get a value to indicate that the hashtable is readonly or not.
Item It is used get or set the value associated with the specified key.
IsSynchronized It is used to get a value to inidicate that an access to hashtable is synchronized (thread safe) or not.
Keys It is used to get the collection of keys in the hashtable.
Values It is used to get the collection of values in the hashtable.

Visual Basic HashTable Methods

Following are the some of commonly used methods of hashtable to perform an operations like add, delete, etc. on elements of hashtable in visual basic programming language.

 

MethodDescription
Add It is used to add an element with specified key and value in hashtable.
Clear It will remove all the elements from hashtable.
Clone It will create a shallow copy of hashtable.
Contains It is used determine whether the hashtable contains a specific key or not.
ContainsKey It is used determine whether the hashtable contains a specific key or not.
ContainsValue It is used determine whether the hashtable contains a specific value or not.
Remove It is used to remove an element with specified key from the hashtable.
GetHash It is used get the hash code for the specified key.

Visual Basic Add Elements to HashTable

In visual basic, while adding elements to hashtable we need to make sure that there will not be any duplicate keys because hashtable will allow us to store duplicate values but keys must be unique to identify the values in the hashtable.

 

In hashtable, we can add key/value pair elements of different data types. Following is the example of adding elements to hashtable in visual basic.

 

Module Module1

    Sub Main(ByVal args As String())

        Dim htbl As Hashtable = New Hashtable()

        htbl.Add("msg", "Welcome")

        htbl.Add("site", "Tutlane")

        htbl.Add(1, 20.5)

        htbl.Add(2, Nothing)

        ' Another way to add elements. If key not exist, then that key adds a new key/value pair.

        htbl(3) = "Tutorials"

        ' Add method will throws an exception if key already exists in hash table

        Try

            htbl.Add(2, 100)

        Catch

            Console.WriteLine("An element with Key = '2' already exists.")

        End Try

        Console.WriteLine("*********HashTable Elements********")

        ' It will return elements as KeyValuePair objects

        For Each item As DictionaryEntry In htbl

            Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value)

        Next

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we created new hashtable (htbl) and adding different data type elements (key/value) to hashtable (htbl) in different ways. As discussed, the Add method will throw an exception in case, if we try to add a key (2) which is already existing so to handle that exception we used try-catch block.

 

When we execute the above visual basic program, we will get the result like as shown below.

 

Visual basic Add Elements to Hashtable Example Result

 

If you observe the above result, we got an exception when we tried to add a key (2) which is already existing and added a key (3) which is not existing in the hashtable.

 

In visual basic, we can also assign key / value pairs to hashtable at the time of initialization like as shown below.

 

Dim htbl As Hashtable = New Hashtable() From {

                                {"msg", "Welcome"},

                                {"site", "Tutlane"},

                                {1, 20.5},

                                {2, Nothing}

                            }

Visual Basic Access HashTable Elements

In visual basic, we have different ways to access hashtable elements i.e. either by using keys or by iterating through a hashtable using For Each loop.

 

Following is the example of accessing hashtable elements in different ways.

 

Module Module1

    Sub Main(ByVal args As String())

        Dim htbl As Hashtable = New Hashtable()

        htbl.Add("msg", "Welcome")

        htbl.Add("site", "Tutlane")

        htbl.Add(1, 20.5F)

        htbl.Add(2, 10)

        Dim msg As String = CStr(htbl("msg"))

        Dim num As Single = CSng(htbl(1))

        Console.WriteLine("*********Access Elements with Keys********")

        Console.WriteLine("Value at Key 'msg': " & msg)

        Console.WriteLine("Value at Key '1': " & num)

        Console.WriteLine("*********Access Elements with Foreach Loop********")

        For Each item As DictionaryEntry In htbl

            Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value)

        Next

        Console.WriteLine("*********HashTable Keys********")

        For Each item In htbl.Keys

            Console.WriteLine("Key = {0}", item)

        Next

        Console.WriteLine("*********HashTable Values********")

        For Each item In htbl.Values

            Console.WriteLine("Value = {0}", item)

        Next

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we are accessing hashtable elements in different ways by using keys, For Each loop and with available properties (Keys, Values) based on our requirements.

 

When we execute the above visual basic program, we will get the result like as shown below.

 

Visual Basic Access Hashtable Elements Example Result

Visual Basic Remove Elements from HashTable

In visual basic, we can delete elements from hashtable by using the Remove() method. Following is the example of deleting the elements from hashtable in visual basic programming language.

 

Module Module1

    Sub Main(ByVal args As String())

        Dim htbl As Hashtable = New Hashtable()

        htbl.Add("msg", "Welcome")

        htbl.Add("site", "Tutlane")

        htbl.Add(1, 20.5F)

        htbl.Add(2, 10)

        htbl.Add(3, 100)

        htbl.Remove(1)

        htbl.Remove("msg")

        Console.WriteLine("*********HashTable Elements********")

        For Each item As DictionaryEntry In htbl

            Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value)

        Next

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we used a Remove() method to delete the particular value of element from hashtable using keys.

 

When we execute the above visual basic program, we will get the result like as shown below.

 

Visual Basic Remove Hashtable Elements Example Result

 

In case, if you want to remove all the elements from hashtable, use Clear() method.

Visual Basic HashTable Check If Element Exists

By using Contains(), ContainsKey() and ContainsValue() methods, we can check whether the specified element exists in hashtable or not. In case, if it exists these methods will return True otherwise False.

 

Following is the example of using Contains(), ContainsKey() and ContainsValue() methods to check for an item exists in hashtable or not in visual basic.

 

Module Module1

    Sub Main(ByVal args As String())

        Dim htbl As Hashtable = New Hashtable()

        htbl.Add("msg", "Welcome")

        htbl.Add("site", "Tutlane")

        htbl.Add(1, 20.5F)

        htbl.Add(2, 10)

        htbl.Add(3, 100)

        Console.WriteLine("Contains Key 4: {0}", htbl.Contains(4))

        Console.WriteLine("Contains Key 2: {0}", htbl.ContainsKey(2))

        Console.WriteLine("Contains Value 'Tutlane': {0}", htbl.ContainsValue("Tutlane"))

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we used a Contains(), ContainsKey() and ContainsValue() methods to check for particular keys and values exists in hashtable (htbl) or not.

 

When we execute the above visual basic program, we will get the result like as shown below.

 

Visual Basic Check Elements Exists in Hashtable or Not Example Result

Visual Basic HashTable Overview

Following are the important points which need to remember about hashtable in visual basic.

 

  • Hashtable is used to store a collection of key/value pairs of different data types and those are organized based on the hash code of the key.
  • Hashtable is a non-generic type of collection so we need to cast hashtable items to appropriate data type before we use it in our application.
  • Hashtable will allow us to store duplicate values but keys must be unique to identify the values in the hashtable.
  • In hashtable, the key cannot be null but the value can be null.
  • We can access hashtable elements either by using keys or with For Each loop. In For Each loop we need to use DictionaryEntry to get a key/value pairs from the hashtable.