Hashtable.Add(Object, Object) Method (System.Collections) (2024)

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

key is null.

An element with the same key already exists in the Hashtable.

The Hashtable is read-only.

-or-

The Hashtable has a fixed size.

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

Hashtable.Add(Object, Object) Method (System.Collections) (2024)

FAQs

How do you add items to a Hashtable? ›

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?
  1. Syntax. public virtual void Add(object key, object value);
  2. Parameters. Key − the specified key(type System. ...
  3. Exceptions: This method throws the following exceptions. ArgumentNullException − When the key is null. ...
  4. Example 1. Open Compiler. ...
  5. Output. ...
  6. Example 2. ...
  7. Output.
Dec 14, 2022

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
  1. Set indx = H(K)
  2. If table location indx already contains the key, no need to insert it. Done!
  3. Else if table location indx is empty, insert key there. Done!
  4. Else collision. Set indx = (indx + 1) mod M.
  5. 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 .

Which is faster, dictionary or 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.

Top Articles
Spyware: What it is, what types exist and how it can be removed - BBVA Pivot Net
What's the Difference Between a Chef and a Cook? | CulinaryLab School
Is Sam's Club Plus worth it? What to know about the premium warehouse membership before you sign up
Chicago Neighborhoods: Lincoln Square & Ravenswood - Chicago Moms
From Algeria to Uzbekistan-These Are the Top Baby Names Around the World
Overnight Cleaner Jobs
Retro Ride Teardrop
Noaa Swell Forecast
Gameplay Clarkston
Best Cav Commanders Rok
Morgan Wallen Pnc Park Seating Chart
Large storage units
Hallelu-JaH - Psalm 119 - inleiding
Ree Marie Centerfold
Notisabelrenu
Bitlife Tyrone's
Daily Voice Tarrytown
Vigoro Mulch Safe For Dogs
How your diet could help combat climate change in 2019 | CNN
Azur Lane High Efficiency Combat Logistics Plan
Craigslist Apartments Baltimore
[PDF] PDF - Education Update - Free Download PDF
Craigslist Roseburg Oregon Free Stuff
Waters Funeral Home Vandalia Obituaries
Delta Math Login With Google
The Bold and the Beautiful
Frequently Asked Questions - Hy-Vee PERKS
Fbsm Greenville Sc
Wasmo Link Telegram
3400 Grams In Pounds
Henry County Illuminate
Cherry Spa Madison
Red Dead Redemption 2 Legendary Fish Locations Guide (“A Fisher of Fish”)
Craigslist en Santa Cruz, California: Tu Guía Definitiva para Comprar, Vender e Intercambiar - First Republic Craigslist
Mississippi weather man flees studio during tornado - video
ESA Science & Technology - The remarkable Red Rectangle: A stairway to heaven? [heic0408]
The Attleboro Sun Chronicle Obituaries
FREE - Divitarot.com - Tarot Denis Lapierre - Free divinatory tarot - Your divinatory tarot - Your future according to the cards! - Official website of Denis Lapierre - LIVE TAROT - Online Free Tarot cards reading - TAROT - Your free online latin tarot re
Free Crossword Puzzles | BestCrosswords.com
Levi Ackerman Tattoo Ideas
Oklahoma City Farm & Garden Craigslist
Phmc.myloancare.com
The Machine 2023 Showtimes Near Roxy Lebanon
Solving Quadratics All Methods Worksheet Answers
Electric Toothbrush Feature Crossword
Skyward Login Wylie Isd
David Turner Evangelist Net Worth
How to Get a Check Stub From Money Network
Provincial Freeman (Toronto and Chatham, ON: Mary Ann Shadd Cary (October 9, 1823 – June 5, 1893)), November 3, 1855, p. 1
Coldestuknow
Affidea ExpressCare - Affidea Ireland
Latest Posts
Article information

Author: Nicola Considine CPA

Last Updated:

Views: 6088

Rating: 4.9 / 5 (49 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Nicola Considine CPA

Birthday: 1993-02-26

Address: 3809 Clinton Inlet, East Aleisha, UT 46318-2392

Phone: +2681424145499

Job: Government Technician

Hobby: Calligraphy, Lego building, Worldbuilding, Shooting, Bird watching, Shopping, Cooking

Introduction: My name is Nicola Considine CPA, I am a determined, witty, powerful, brainy, open, smiling, proud person who loves writing and wants to share my knowledge and understanding with you.