Adds an element with the specified key and value into the Hashtable.
public: virtual void Add(System::Object ^ key, System::Object ^ value);
public virtual void Add (object key, object value);
public virtual void Add (object key, object? value);
abstract member Add : obj * obj -> unitoverride this.Add : obj * obj -> unit
Public Overridable Sub Add (key As Object, value As Object)
Parameters
- key
- Object
The key of the element to add.
- value
- Object
The value of the element to add. The value can be null
.
Implements
Exceptions
An element with the same key already exists in the Hashtable.
Examples
The following example shows how to add elements to the Hashtable.
using namespace System;using namespace System::Collections;void PrintKeysAndValues( Hashtable^ myHT );int main(){ // Creates and initializes a new Hashtable. Hashtable^ myHT = gcnew Hashtable; myHT->Add( "one", "The" ); myHT->Add( "two", "quick" ); myHT->Add( "three", "brown" ); myHT->Add( "four", "fox" ); // Displays the Hashtable. Console::WriteLine( "The Hashtable contains the following:" ); PrintKeysAndValues( myHT );}void PrintKeysAndValues( Hashtable^ myHT ){ Console::WriteLine( "\t-KEY-\t-VALUE-" ); IEnumerator^ myEnum = myHT->GetEnumerator(); while ( myEnum->MoveNext() ) { DictionaryEntry de = *safe_cast<DictionaryEntry ^>(myEnum->Current); Console::WriteLine( "\t{0}:\t{1}", de.Key, de.Value ); } Console::WriteLine();}/* This code produces the following output. The Hashtable contains the following: -KEY- -VALUE- two: quick three: brown four: fox one: The */
using System;using System.Collections;public class SamplesHashtable{ public static void Main() { // Creates and initializes a new Hashtable. var myHT = new Hashtable(); myHT.Add("one", "The"); myHT.Add("two", "quick"); myHT.Add("three", "brown"); myHT.Add("four", "fox"); // Displays the Hashtable. Console.WriteLine("The Hashtable contains the following:"); PrintKeysAndValues(myHT); } public static void PrintKeysAndValues( Hashtable myHT ) { Console.WriteLine("\t-KEY-\t-VALUE-"); foreach (DictionaryEntry de in myHT) Console.WriteLine($"\t{de.Key}:\t{de.Value}"); Console.WriteLine(); }}/*This code produces the following output.The Hashtable contains the following: -KEY- -VALUE- two: quick three: brown four: fox one: The*/
Imports System.CollectionsPublic Class SamplesHashtable Public Shared Sub Main() ' Creates and initializes a new Hashtable. Dim myHT As New Hashtable() myHT.Add("one", "The") myHT.Add("two", "quick") myHT.Add("three", "brown") myHT.Add("four", "fox") ' Displays the Hashtable. Console.WriteLine("The Hashtable contains the following:") PrintKeysAndValues(myHT) End Sub Public Shared Sub PrintKeysAndValues(myHT As Hashtable) Console.WriteLine(vbTab + "-KEY-" + vbTab + "-VALUE-") For Each de As DictionaryEntry In myHT Console.WriteLine(vbTab + "{0}:" + vbTab + "{1}", de.Key, de.Value) Next Console.WriteLine() End SubEnd Class' This code produces the following output.' ' The Hashtable contains the following:' -KEY- -VALUE-' two: quick' one: The' three: brown' four: fox'
Remarks
A key cannot be null
, but a value can be.
An object that has no correlation between its state and its hash code value should typically not be used as the key. For example, String objects are better than StringBuilder objects for use as keys.
You can also use the Item[] property to add new elements by setting the value of a key that does not exist in the Hashtable; for example, myCollection["myNonexistentKey"] = myValue
. However, if the specified key already exists in the Hashtable, setting the Item[] property overwrites the old value. In contrast, the Add method does not modify existing elements.
If Count is less than the capacity of the Hashtable, this method is an O(1)
operation. If the capacity needs to be increased to accommodate the new element, this method becomes an O(n)
operation, where n
is Count.
Applies to
See also
FAQs
And, you can add keys and values to a hashtable using the addition operator ( + ) to add a hashtable to an existing hashtable. For example, the following statement adds a Time key with a value of Now to the hashtable in the $hash variable. You can also add values that are stored in variables.
Which method is used to add elements in a Hashtable? ›
Add(Object, Object) Method is used to adds an element with the specified key and value into the Hashtable. Syntax: public virtual void Add(object key, object value);
How to add key-value to Hashtable in C#? ›
How to Add Items to the Hashtable Collection?
- Syntax. public virtual void Add(object key, object value);
- Parameters. Key − the specified key(type System. ...
- Exceptions: This method throws the following exceptions. ArgumentNullException − When the key is null. ...
- Example 1. Open Compiler. ...
- Output. ...
- Example 2. ...
- Output.
How do I insert values into a Hashtable? ›
To insert a new item in the table, we hash the key to determine which list the item goes on, and then insert the item at the beginning of the list. For example, to insert 11, we divide 11 by 8 giving a remainder of 3. Thus, 11 goes on the list starting at HashTable[3].
How to add objects in HashMap? ›
put(K key, V value) method
This method is used to set the value with the corresponding key in HashMap. It inserts the entry(Key-Value) in the hashmap. If the HashMap already contained the key, then the old value is replaced by a new Value. It returns null if there is no value presented in the hashmap for the given key.
What is a HashTable in a collection? ›
The Hashtable class in Java is one of the oldest members of the Java Collection Framework. A hash table is an unordered collection of key-value pairs, with a unique key for each value. In a hash table, data is stored in an array of list format, with a distinct index value for each data value.
How to insert an element in hash table using linear probing? ›
Linear probing: inserting a key
- Set indx = H(K)
- If table location indx already contains the key, no need to insert it. Done!
- Else if table location indx is empty, insert key there. Done!
- Else collision. Set indx = (indx + 1) mod M.
- If indx == H(K), table is full! (Throw an exception, or enlarge table.) Else go to 2.
What is hash table methods? ›
Hash tables are a type of data structure in which the address/ index value of the data element is generated from a hash function. This enables very fast data access as the index value behaves as a key for the data value.
Can we add duplicate key in Hashtable? ›
A Hashtable does not accept duplicate keys. If you add a duplicate key the value will be replaced for that key. Here, you can see that when the key 1 is added again, the value is replaced with Kumaran. So, Hashtable does not accept duplicate keys.
Can a Hashtable have duplicate keys in C#? ›
A HashTable collection stores a ( Key , Value ) pair and uses the Key to hash and obtain the storage location. The Key is immutable and cannot have duplicate entries in the HashTable .
A Dictionary<TKey,TValue> of a specific type (other than Object) provides better performance than a Hashtable for value types. This is because the elements of Hashtable are of type Object; therefore, boxing and unboxing typically occur when you store or retrieve a value type.
Which method is used to add element in Hashtable? ›
util. Hashtable. put() method of Hashtable is used to insert a mapping into a table. This means we can insert a specific key and the value it is mapping to into a particular table.
What is Hashtable collection in C#? ›
A hashtable is a general-purpose dictionary collection. Each item within the collection is a DictionaryEntry object with two properties: a key object and a value object. These are known as Key/Value pairs.
What is the order of insertion in Hashtable? ›
Hashtable does not maintains insertion order in java. LinkedHashMap maintains insertion order in java. TreeMap is sorted by natural order of keys in java. HashMap is not synchronized, hence its operations are faster as compared to Hashtable.
How do you add a record to a hash table? ›
To insert data into a hash table, you must use the hash function to generate the index of the position in the array that will be used to store the data. Remember that the key must be stored as part of, or alongside, the data.
How do you fill a hash table? ›
To store an element in the hash table you must insert it into a specific linked list. If there is any collision (i.e. two different elements have same hash value) then store both the elements in the same linked list. The cost of a lookup is that of scanning the entries of the selected linked list for the required key.
How do you add a value to a hash set? ›
Java HashSet add() Method
The add() is a method of Java HashSet class which adds the specified element to this set if this set contains no element. If it is already contain the element, the call leaves the set unchanged and returns false.
How are items found in a hash table? ›
A hash table uses a hash function to compute an index, also called a hash code, into an array of buckets or slots, from which the desired value can be found. During lookup, the key is hashed and the resulting hash indicates where the corresponding value is stored.