Thursday, May 22, 2008

kalavathi guna

Hashtable Class

Represents a collection of key/value pairs that are organized based on the hash code of the key.

Namespace: System.Collections
Assembly: mscorlib (in mscorlib.dll)
Syntax
Visual Basic (Declaration)

_
_
Public Class Hashtable _
Implements IDictionary, ICollection, IEnumerable, ISerializable, _
IDeserializationCallback, ICloneable

Visual Basic (Usage)

Dim instance As Hashtable

C#

[SerializableAttribute]
[ComVisibleAttribute(true)]
public class Hashtable : IDictionary, ICollection,
IEnumerable, ISerializable, IDeserializationCallback, ICloneable

Visual C++

[SerializableAttribute]
[ComVisibleAttribute(true)]
public ref class Hashtable : IDictionary,
ICollection, IEnumerable, ISerializable, IDeserializationCallback, ICloneable

J#

/** @attribute SerializableAttribute */
/** @attribute ComVisibleAttribute(true) */
public class Hashtable implements IDictionary,
ICollection, IEnumerable, ISerializable, IDeserializationCallback, ICloneable

JScript

public class Hashtable implements IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback, ICloneable

Remarks

Each element is a key/value pair stored in a DictionaryEntry object. A key cannot be nullNothingnullptra null reference (Nothing in Visual Basic), but a value can be.

The objects used as keys by a Hashtable are required to override the Object..::.GetHashCode method (or the IHashCodeProvider interface) and the Object..::.Equals method (or the IComparer interface). The implementation of both methods and interfaces must handle case sensitivity the same way; otherwise, the Hashtable might behave incorrectly. For example, when creating a Hashtable, you must use the CaseInsensitiveHashCodeProvider class (or any case-insensitive IHashCodeProvider implementation) with the CaseInsensitiveComparer class (or any case-insensitive IComparer implementation).

Furthermore, these methods must produce the same results when called with the same parameters while the key exists in the Hashtable. An alternative is to use a Hashtable constructor with an IEqualityComparer parameter. If key equality were simply reference equality, the inherited implementation of Object..::.GetHashCode and Object..::.Equals would suffice.

Key objects must be immutable as long as they are used as keys in the Hashtable.

When an element is added to the Hashtable, the element is placed into a bucket based on the hash code of the key. Subsequent lookups of the key use the hash code of the key to search in only one particular bucket, thus substantially reducing the number of key comparisons required to find an element.

The load factor of a Hashtable determines the maximum ratio of elements to buckets. Smaller load factors cause faster average lookup times at the cost of increased memory consumption. The default load factor of 1.0 generally provides the best balance between speed and size. A different load factor can also be specified when the Hashtable is created.

As elements are added to a Hashtable, the actual load factor of the Hashtable increases. When the actual load factor reaches the specified load factor, the number of buckets in the Hashtable is automatically increased to the smallest prime number that is larger than twice the current number of Hashtable buckets.

Each key object in the Hashtable must provide its own hash function, which can be accessed by calling GetHash. However, any object implementing IHashCodeProvider can be passed to a Hashtable constructor, and that hash function is used for all objects in the table.

The capacity of a Hashtable is the number of elements the Hashtable can hold. As elements are added to a Hashtable, the capacity is automatically increased as required through reallocation.
vb# c#

The foreach statement of the C# language (for each in Visual Basic) requires the type of each element in the collection. Since each element of the Hashtable is a key/value pair, the element type is not the type of the key or the type of the value. Instead, the element type is DictionaryEntry. For example:
C#
Copy Code

foreach (DictionaryEntry de in myHashtable) {...}

Visual Basic
Copy Code

For Each de as DictionaryEntry In myHashtable
...
Next de

vb# c#

The foreach statement is a wrapper around the enumerator, which only allows reading from, not writing to, the collection.

Because serializing and deserializing an enumerator for a Hashtable can cause the elements to become reordered, it is not possible to continue enumeration without calling the Reset method.
[Note] Note:

Because keys can be inherited and their behavior changed, their absolute uniqueness cannot be guaranteed by comparisons using the Equals method.
Examples

The following example shows how to create, initialize and perform various functions to a Hashtable and how to print out its keys and values.
Visual Basic
Copy Code

Imports System
Imports System.Collections

Module Example

Sub Main()

' Create a new hash table.
'
Dim openWith As New Hashtable()

' Add some elements to the hash table. There are no
' duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")

' The Add method throws an exception if the new key is
' already in the hash table.
Try
openWith.Add("txt", "winword.exe")
Catch
Console.WriteLine("An element with Key = ""txt"" already exists.")
End Try

' The Item property is the default property, so you
' can omit its name when accessing elements.
Console.WriteLine("For key = ""rtf"", value = {0}.", _
openWith("rtf"))

' The default Item property can be used to change the value
' associated with a key.
openWith("rtf") = "winword.exe"
Console.WriteLine("For key = ""rtf"", value = {0}.", _
openWith("rtf"))

' If a key does not exist, setting the default Item property
' for that key adds a new key/value pair.
openWith("doc") = "winword.exe"

' ContainsKey can be used to test keys before inserting
' them.
If Not openWith.ContainsKey("ht") Then
openWith.Add("ht", "hypertrm.exe")
Console.WriteLine("Value added for key = ""ht"": {0}", _
openWith("ht"))
End If

' When you use foreach to enumerate hash table elements,
' the elements are retrieved as KeyValuePair objects.
Console.WriteLine()
For Each de As DictionaryEntry In openWith
Console.WriteLine("Key = {0}, Value = {1}", _
de.Key, de.Value)
Next de

' To get the values alone, use the Values property.
Dim valueColl As ICollection = openWith.Values

' The elements of the ValueCollection are strongly typed
' with the type that was specified for hash table values.
Console.WriteLine()
For Each s As String In valueColl
Console.WriteLine("Value = {0}", s)
Next s

' To get the keys alone, use the Keys property.
Dim keyColl As ICollection = openWith.Keys

' The elements of the KeyCollection are strongly typed
' with the type that was specified for hash table keys.
Console.WriteLine()
For Each s As String In keyColl
Console.WriteLine("Key = {0}", s)
Next s

' Use the Remove method to remove a key/value pair.
Console.WriteLine(vbLf + "Remove(""doc"")")
openWith.Remove("doc")

If Not openWith.ContainsKey("doc") Then
Console.WriteLine("Key ""doc"" is not found.")
End If

End Sub

End Module

' This code example produces the following output:
'
'An element with Key = "txt" already exists.
'For key = "rtf", value = wordpad.exe.
'For key = "rtf", value = winword.exe.
'Value added for key = "ht": hypertrm.exe
'
'Key = dib, Value = paint.exe
'Key = txt, Value = notepad.exe
'Key = ht, Value = hypertrm.exe
'Key = bmp, Value = paint.exe
'Key = rtf, Value = winword.exe
'Key = doc, Value = winword.exe
'
'Value = paint.exe
'Value = notepad.exe
'Value = hypertrm.exe
'Value = paint.exe
'Value = winword.exe
'Value = winword.exe
'
'Key = dib
'Key = txt
'Key = ht
'Key = bmp
'Key = rtf
'Key = doc
'
'Remove("doc")
'Key "doc" is not found.

C#
Copy Code

using System;
using System.Collections;

class Example
{
public static void Main()
{
// Create a new hash table.
//
Hashtable openWith = new Hashtable();

// Add some elements to the hash table. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");

// The Add method throws an exception if the new key is
// already in the hash table.
try
{
openWith.Add("txt", "winword.exe");
}
catch
{
Console.WriteLine("An element with Key = \"txt\" already exists.");
}

// The Item property is the default property, so you
// can omit its name when accessing elements.
Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);

// The default Item property can be used to change the value
// associated with a key.
openWith["rtf"] = "winword.exe";
Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);

// If a key does not exist, setting the default Item property
// for that key adds a new key/value pair.
openWith["doc"] = "winword.exe";

// ContainsKey can be used to test keys before inserting
// them.
if (!openWith.ContainsKey("ht"))
{
openWith.Add("ht", "hypertrm.exe");
Console.WriteLine("Value added for key = \"ht\": {0}", openWith["ht"]);
}

// When you use foreach to enumerate hash table elements,
// the elements are retrieved as KeyValuePair objects.
Console.WriteLine();
foreach( DictionaryEntry de in openWith )
{
Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
}

// To get the values alone, use the Values property.
ICollection valueColl = openWith.Values;

// The elements of the ValueCollection are strongly typed
// with the type that was specified for hash table values.
Console.WriteLine();
foreach( string s in valueColl )
{
Console.WriteLine("Value = {0}", s);
}

// To get the keys alone, use the Keys property.
ICollection keyColl = openWith.Keys;

// The elements of the KeyCollection are strongly typed
// with the type that was specified for hash table keys.
Console.WriteLine();
foreach( string s in keyColl )
{
Console.WriteLine("Key = {0}", s);
}

// Use the Remove method to remove a key/value pair.
Console.WriteLine("\nRemove(\"doc\")");
openWith.Remove("doc");

if (!openWith.ContainsKey("doc"))
{
Console.WriteLine("Key \"doc\" is not found.");
}
}
}

/* This code example produces the following output:

An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Value added for key = "ht": hypertrm.exe

Key = dib, Value = paint.exe
Key = txt, Value = notepad.exe
Key = ht, Value = hypertrm.exe
Key = bmp, Value = paint.exe
Key = rtf, Value = winword.exe
Key = doc, Value = winword.exe

Value = paint.exe
Value = notepad.exe
Value = hypertrm.exe
Value = paint.exe
Value = winword.exe
Value = winword.exe

Key = dib
Key = txt
Key = ht
Key = bmp
Key = rtf
Key = doc

Remove("doc")
Key "doc" is not found.
*/

Inheritance Hierarchy
System..::.Object
System.Collections..::.Hashtable
System.Configuration..::.SettingsAttributeDictionary
System.Configuration..::.SettingsContext
System.Data..::.PropertyCollection
System.Printing.IndexedProperties..::.PrintPropertyDictionary
Thread Safety

Hashtable is thread safe for use by multiple reader threads and a single writing thread. It is thread safe for multi-thread use when only one of the threads perform write (update) operations, which allows for lock-free reads provided that the writers are serialized to the Hashtable. To support multiple writers all operations on the Hashtable must be done through the wrapper returned by the Synchronized method, provided that there are no threads reading the Hashtable object.

Enumerating through a collection is intrinsically not a thread safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.
Platforms

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information
.NET Framework
Supported in: 3.5, 3.0 SP1, 3.0, 2.0 SP1, 2.0, 1.1, 1.0
.NET Compact Framework
Supported in: 3.5, 2.0, 1.0
XNA Framework
Supported in: 1.0
See Also
Reference
Hashtable Members
System.Collections Namespace
IDictionary
IHashCodeProvider
Object..::.GetHashCode
Object..::.Equals
DictionaryEntry
System.Collections.Generic..::.Dictionary<(Of <(TKey, TValue>)>)
IEqualityComparer
Tags What's this?: Add a tag Add Cancel
Flag as ContentBug
Community Content What is Community Content?
Add new content
Hash Table sample using PowerShell Thomas Lee | Edit | Show History
Please Wait Please Wait

# Get-Hashtable.ps1

# MSDN sample - recoded with PowerShell

# thomas lee - tfl@psp.co.uk

# create new hash table
$openWith = @{}


# Add some elements to the hash table. There are no


#duplicate keys, but some of the values are duplicates.



$openWith.Add("txt", "notepad.exe")
$openWith.Add("dib", "paint.exe"


# Add in a powershell way!
$openwith += @{"bmp"="paint.exe"


# or
$wordpad = "wordpad.exe"
$openwith += @{"rtf"=$word


# Display the Hash table
"The Hash Table so far"
$openwith


# The Add method throws an exception if the new key is
# already in the hash table.



#first catch exception
trap [Exception] {
"***"
write-host "*** An element with Key = `"txt`" already exists."
"***"
continue
}


# now the offending line.
"";"Trying to add an entry with an existing key"
$openWith.Add("txt", "winword.exe");
"Continuing";""


# The Item property is the default property, so you
# can omit its name when accessing elements
# A non-existing key comes up empty
"For key = `"rtf`", value = {0}." -f $openWith["rtf"]


# The default Item property can be used to change the value
# associated with a key.


# add an entry for RTF
$openWith["rtf"] = "winword.exe";
"For key = `"rtf`", value = {0}." -f $openWith["rtf"]


# If a key does not exist, setting the default Item property
# for that key adds a new key/value pair.
$openWith["doc"] = "winword.exe"


# Note Progress with this hashtable
"";"The Hash Table so far:"
$openwith
""


# The ContainsKey method can be used to test keys before inserting them.
# test the "ht" key before adding it into the hashtable
if (!$openWith.ContainsKey("ht")) {
$openWith.Add("ht", "hypertrm.exe")
"Value added for key = `"ht`": {0}" -f $openWith["ht"]
}


"{0} elements in the hash table as follows:" -f $openwith.count
$openwith





# To get the values alone, use the Values property.
$valueColl = $openWith.Values


# To get the values alone, use the Values property.
$valueColl = $openWith.Values


# The elements of the ValueCollection are strongly typed
# with the type that was specified for hash table values.
"";"Value Entries:"
foreach( $s in $valueColl ) {
"Value = {0}" -f $s
}


# To get the keys alone, use the Keys property.
$keyColl = $openWith.Keys


# The elements of the KeyCollection are strongly typed
# with the type that was specified for hash table keys.
"";"Key Entries"
foreach( $s in $keyColl ){
"Key = {0}" -f $s
}


# Use the Remove method to remove a key/value pair.
"`nRemoving(`"doc`")"
$openWith.Remove("doc")


# See if it's tjhere
if (!$openWith.ContainsKey("doc")) {
"Key `"doc`" is not found."
}

No comments: