C#でHashtableが固定サイズかどうかを確認する方法
C# の Hashtable(ハッシュテーブル)が固定サイズを持っているかどうかを確認するには、IsFixedSize プロパティを使用します。このプロパティは、コレクションが固定サイズの場合に true、要素の追加や削除が可能な可変サイズの場合に false を返します。通常、new Hashtable() で作成した Hashtable は動的にサイズが変更されるため、false が返されます。
例1:IsFixedSizeプロパティの基本的な使い方
以下のコードでは、初期容量 10 の Hashtable を作成し、複数のキーと値を追加したうえで、IsFixedSize プロパティの値を出力しています。
using System;
using System.Collections;
public class Demo {
public static void Main(){
Hashtable hash = new Hashtable(10);
hash.Add("1", "A");
hash.Add("2", "B");
hash.Add("3", "C");
hash.Add("4", "D");
hash.Add("5", "E");
hash.Add("6", "F");
hash.Add("7", "G");
hash.Add("8", "H");
hash.Add("9", "I");
hash.Add("10", "J");
Console.WriteLine("Is the Hashtable having fixed size? = "+hash.IsFixedSize);
}
}出力
上記のコードを実行すると、次のような結果が表示されます。
Is the Hashtable having fixed size? = False
この結果から、初期容量を指定して作成した場合でも、Hashtable はデフォルトでは固定サイズにならず、必要に応じて自動的に拡張されることがわかります。
例2:キーと値のペアを表示しながら確認する
続いて、別の例を見てみましょう。ここでは Hashtable にキーと値のペアを追加し、その内容を foreach ループで列挙したあと、IsFixedSize プロパティを確認しています。
using System;
using System.Collections;
public class Demo {
public static void Main(){
Hashtable hash = new Hashtable();
hash.Add("One", "Katie");
hash.Add("Two", "John");
hash.Add("Three", "Barry");
hash.Add("Four", "");
hash.Add("Five", "Harry");
hash.Add("Six", "F");
hash.Add("Seven", "Tom");
hash.Add("Eight", "Andy");
hash.Add("Nine", "I");
hash.Add("Ten", "Tim");
Console.WriteLine("Hashtable Key and Value pairs...");
foreach(DictionaryEntry entry in hash){
Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
}
Console.WriteLine("Is the Hashtable having fixed size? = "+hash.IsFixedSize);
}
}出力
実行すると、次のような結果が出力されます。
Hashtable Key and Value pairs... One and Katie Ten and Tim Five and Harry Three and Barry Seven and Tom Two and John Four and Eight and Andy Nine and I Six and F Is the Hashtable having fixed size? = False
ポイント解説
- foreach ループでは、各要素を
DictionaryEntry型として取り出すことで、Hashtable 内のすべてのキーと値のペアを列挙できます。 - Hashtable は格納順序を保証しないため、出力順序が追加順と異なる点に注意してください。
- 最終行の
Falseという出力により、この Hashtable が可変サイズであることが確認できます。
このように、IsFixedSize プロパティを使えば、Hashtable が固定サイズかどうかを簡単にプログラムから判定できます。固定サイズのコレクションが必要な場合は、ArrayList.FixedSize() メソッドなどでラップされたコレクションを利用する方法もあります。
-
C#で配列のサイズが固定されているかどうかを確認する方法
C#で配列のサイズが固定されているかどうかを確認するには、IsFixedSizeプロパティを使用します。このプロパティは、配列が固定サイズを持つ場合にtrueを返す真偽値です。以下のサンプルコードで、その動作を詳しく見ていきましょう。 サンプルコード using System; public class Demo { public static void Main(){ string[] products = new string[] { "Electronics",
-
C#におけるDictionaryとHashtableの違いを徹底解説
C#でキーと値のペアを管理する際によく使われるのが、HashtableとDictionaryの2つのコレクションです。結論から言えば、HashtableはDictionaryよりも低速であり、厳密に型指定されたコレクションでは、Dictionaryの方が高速に動作します。 Hashtableとは Hashtableクラスは、キーのハッシュコードに基づいて整理された、キーと値のペアのコレクションを表します。コレクション内の各要素には、キーを使ってアクセスします。HashtableはSystem.Collections名前空間に属する非ジェネリック型のため、格納される値はすべてobject型として