今天复习随机算法的时候,顺便想到的,大家做做看 (环境vs2003),如果需要我会提供答案。
using System;
using System.Collections;
namespace HashTable
{
public class MyKey
{
public int Key
{
set
{
key = value;
}
}
private int key=0;
public MyKey(int num)
{
key=num;
}
public override int GetHashCode()
{
return key%5;
}
public override bool Equals(object obj)
{
return key==((MyKey)obj).key;
}
}
class HashTableTest
{
[STAThread]
static void Main(string[] args)
{
MyKey key1=new MyKey(10);
Hashtable ht=new Hashtable();
ht.Add(key1,"Key1");
key1.Key=11;
bool isContained=ht.ContainsKey(key1);
Console.Out.WriteLine("Is key1 contained in hashtable? {0}", isContained);
MyKey key2=new MyKey(10);
ht.Add(key2,"key2");
Console.Out.WriteLine("Hashtable counts:"+ht.Count);
MyKey key3=new MyKey(15);
ht.Add(key3,"key3");
Console.Out.WriteLine("Hashtable counts:"+ht.Count);
MyKey key4=new MyKey(10);
ht.Add(key4,"key4");
}
}
}
using System;
using System.Collections;
namespace HashTable
{
public class MyKey
{
public int Key
{
set
{
key = value;
}
}
private int key=0;
public MyKey(int num)
{
key=num;
}
public override int GetHashCode()
{
return key%5;
}
public override bool Equals(object obj)
{
return key==((MyKey)obj).key;
}
}
class HashTableTest
{
[STAThread]
static void Main(string[] args)
{
MyKey key1=new MyKey(10);
Hashtable ht=new Hashtable();
ht.Add(key1,"Key1");
key1.Key=11;
bool isContained=ht.ContainsKey(key1);
Console.Out.WriteLine("Is key1 contained in hashtable? {0}", isContained);
MyKey key2=new MyKey(10);
ht.Add(key2,"key2");
Console.Out.WriteLine("Hashtable counts:"+ht.Count);
MyKey key3=new MyKey(15);
ht.Add(key3,"key3");
Console.Out.WriteLine("Hashtable counts:"+ht.Count);
MyKey key4=new MyKey(10);
ht.Add(key4,"key4");
}
}
}