Csharp/C Sharp/Collections Data Structure/Hashtable — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 11:39, 26 мая 2010

Add value to Hashtable and loop through the value key pairs

using System;
using System.Collections;
public class HashPut {
  public static void Main( ) {
    String[] identifiers ={"A","B","C","D","E","F","G","H","I","J","K","L"}; 
    String[] types = {"1","2","3","4","5","6","7","8","9","10","11","12"}; 
    Hashtable table = new Hashtable(23);
    
    for(int i = 0; i < identifiers.Length; i++) 
      table.Add(identifiers[i], types[i]);
    
    Console.WriteLine("The value of F is {0}",table["F"]);
    Console.WriteLine("The keys are:");
    
    foreach (DictionaryEntry entry in table) 
      Console.Write("{0} ", entry.Key);
   }
}


Compares the efficiency of the hash map implementation with the tree map

using System;
using System.Collections;
public class CompareMaps {
  public const int MAX  = 50000000;
  public static String time(IDictionary map) {
    Object value = null;
    long starttime = Environment.TickCount;
    for (int i = 0; i < MAX; i++) {
        value = map[i];
    } 
    long stoptime = Environment.TickCount;
    return value + " took " + (stoptime - starttime);
  }          
  
  public static void Main(String[] args) {
    int SIZE = 1000;
    IDictionary hash = new Hashtable(2*SIZE);
    IDictionary tree = new SortedList();
    
    Random random = new Random();
    int i = random.Next(5000000);
    
    for (int j = 0; j < SIZE; j++) {
       if(!hash.Contains(i))
          hash.Add(i, i);
       if(!tree.Contains(i))
          tree.Add(i, i);
    }
    Console.WriteLine("Hash for {0}", time(hash));
    Console.WriteLine("Tree for {0}", time(tree));
  }
}


Demonstrate Hashtable

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Demonstrate Hashtable. 
 
using System; 
using System.Collections; 
 
public class HashtableDemo { 
  public static void Main() { 
    // Create a hash table. 
    Hashtable ht = new Hashtable(); 
     
    // Add elements to the table 
    ht.Add("house", "Dwelling"); 
    ht.Add("car", "Means of transport"); 
    ht.Add("book", "Collection of printed words"); 
    ht.Add("apple", "Edible fruit"); 
 
    // Can also add by using the indexer. 
    ht["tractor"] = "farm implement"; 
 
    // Get a collection of the keys. 
    ICollection c = ht.Keys; 
 
    // Use the keys to obtain the values. 
    foreach(string str in c) 
      Console.WriteLine(str + ": " + ht[str]); 
  } 
}


Enumerating a hash table collection

using System;
using System.Collections;
class Test{
  public static void Main() {
       Hashtable ht = new Hashtable(10);
    
       // Add strings to the hashtable associated with a
       // key value (integer).
    
       ht.Add( 100, "Z");
       ht.Add( 200, "A");
       ht.Add( 300, "B");
       ht.Add( 400, "S");
       ht.Add( 500, "G");
    
       foreach ( DictionaryEntry de in ht ) {
         Console.WriteLine( "Entry Key {0} Value {1}", de.Key, de.Value );
       }
  }
}


Get IDictionaryEnumerator enumerator from Hashtable

using System;
using System.Collections;
public class Starter {
    public static void Main() {
        Hashtable zHash = new Hashtable();
        zHash.Add("one", 1);
        zHash.Add("two", 2);
        zHash.Add("three", 3);
        zHash.Add("four", 4);
        IDictionaryEnumerator e = zHash.GetEnumerator();
        while (e.MoveNext()) {
            Console.WriteLine(
                "{0} {1}",
                e.Key, e.Value);
        }
    }
}


illustrates the use of a Hashtable

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example11_6.cs illustrates the use of a Hashtable
*/
using System;
using System.Collections;
public class Example11_6
{
  public static void Main()
  {
    // create a Hashtable object
    Hashtable myHashtable = new Hashtable();
    // add elements containing US state abbreviations and state
    // names to myHashtable using the Add() method
    myHashtable.Add("AL", "Alabama");
    myHashtable.Add("CA", "California");
    myHashtable.Add("FL", "Florida");
    myHashtable.Add("NY", "New York");
    myHashtable.Add("WY", "Wyoming");
    // display the Count property
    Console.WriteLine("myHashtable.Count = " + myHashtable.Count);
    // lookup the state name for "CA"
    string myState = (string) myHashtable["CA"];
    Console.WriteLine("myState = " + myState);
    // display the keys for myHashtable using the Keys property
    foreach (string myKey in myHashtable.Keys)
    {
      Console.WriteLine("myKey = " + myKey);
    }
    // display the values for myHashtable using the Values property
    foreach(string myValue in myHashtable.Values)
    {
      Console.WriteLine("myValue = " + myValue);
    }
  }
}


illustrates the use of the Hashtable methods

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example11_7.cs illustrates the use of the Hashtable methods
*/
using System;
using System.Collections;
public class Example11_7
{
  public static void Main()
  {
    // create a Hashtable object
    Hashtable myHashtable = new Hashtable();
    // add elements containing US state abbreviations and state
    // names to myHashtable using the Add() method
    myHashtable.Add("AL", "Alabama");
    myHashtable.Add("CA", "California");
    myHashtable.Add("FL", "Florida");
    myHashtable.Add("NY", "New York");
    myHashtable.Add("WY", "Wyoming");
    // display the keys for myHashtable using the Keys property
    foreach (string myKey in myHashtable.Keys)
    {
      Console.WriteLine("myKey = " + myKey);
    }
    // display the values for myHashtable using the Values property
    foreach(string myValue in myHashtable.Values)
    {
      Console.WriteLine("myValue = " + myValue);
    }
    // use the ContainsKey() method to check if myHashtable
    // contains the key "FL"
    if (myHashtable.ContainsKey("FL"))
    {
      Console.WriteLine("myHashtable contains the key FL");
    }
    // use the ContainsValue() method to check if myHashtable
    // contains the value "Florida"
    if (myHashtable.ContainsValue("Florida"))
    {
      Console.WriteLine("myHashtable contains the value Florida");
    }
    // use the Remove() method to remove FL from myHashtable
    Console.WriteLine("Removing FL from myHashtable");
    myHashtable.Remove("FL");
    // get the number of elements in myHashtable using the Count
    // property
    int count = myHashtable.Count;
    // copy the keys from myHashtable into an array using
    // the CopyTo() method and then display the array contents
    Console.WriteLine("Copying keys to myKeys array");
    string[] myKeys = new string[count];
    myHashtable.Keys.CopyTo(myKeys, 0);
    for (int counter = 0; counter < myKeys.Length; counter++)
    {
      Console.WriteLine("myKeys[" + counter + "] = " +
        myKeys[counter]);
    }
    // copy the values from myHashtable into an array using
    // the CopyTo() method and then display the array contents
    Console.WriteLine("Copying values to myValues array");
    string[] myValues = new string[count];
    myHashtable.Values.CopyTo(myValues, 0);
    for (int counter = 0; counter < myValues.Length; counter++)
    {
      Console.WriteLine("myValues[" + counter + "] = " +
        myValues[counter]);
    }
  }
}


Implement GetHashCode method and store it in a hashtable

using System;
using System.Collections;
public class GoodCompare {
  public static void Main() {
    Name president = new Name ("A", "B");
    Name first = new Name ("C", "D");
    
    Hashtable m = new Hashtable();
    m.Add(president, "first");
    Console.WriteLine(m.Contains(first));
    Console.WriteLine(m[first]); 
  }
}

public class Name {
  protected String first;
  protected char initial;
  protected String last;
          
  public Name(String f, String l) {
    first = f; 
    last = l; 
  }
  public Name(String f, char i, String l) : this(f,l) {
    initial = i;  
  } 
  public override String ToString() {
    if (initial == "\u0000")
       return first + " " + last;
    else  
       return first + " " + initial + " " + last;
  }
  public override bool Equals(Object o) {
    if (!(o is Name))
       return false;
    Name name = (Name)o;
    return first == name.first && initial == name.initial
             && last == name.last;
  }
  public override int GetHashCode() {
    return first.GetHashCode() + (int)initial 
                             + last.GetHashCode();
  }
}