ကြၽန္ေတာ္တို႔ array ေတြ ေၾကျငာတဲ႔ အခါမွာ integer array ေၾကျငာရင္ integer ပဲ သိမ္းလို႔ ရပါမယ္။ string array ဆိုရင္လည္း string ေတြပဲ သိမ္းမွာေပါ့။ ဒီလိုမဟုတ္ပဲ ကိုယ္ၾကိဳက္တဲ႔ data type ကို သိမ္းလို႔ ရခ်င္ရင္ေတာ့ object array ေဆာက္ေပးရပါတယ္။
object[] arr = new object[3]; arr[0] = 1; arr[1] = 2.2; arr[2] = "abcdefg";
အခုထိ ကြၽန္ေတာ္တို႔ သံုးခဲ႔တဲ႔ array ေတြရဲ႕ size ဟာ static size ျဖစ္ပါတယ္။ ကြၽန္ေတာ္တို႔ array ကို ၃ ခန္းေၾကျငာလိုက္ရင္ ၃ ခန္းထက္ပိုျပီး တန္ဖိုးထည့္လို႔ မရပါဘူး။ ကြၽန္ေတာ္တို႔ သံုးမယ့္ array ရဲ႕ size ကို dynamic size အျဖစ္သံုးခ်င္တယ္ ဆိုရင္ေတာ့ သီးျခားအေနနဲ႔ collection class ေတြကို သံုးၾကရမွာပါ။ ပထမဆံုးအေနနဲ႔ ArrayList Class အေၾကာင္း စေျပာပါ့မယ္။
ArrayList Class က array တစ္ခုလိုမ်ိဳး အလုပ္လုပ္ေပးပါတယ္။ သူက variant size ပါ။ စေၾကျငာခ်င္းခ်င္းမွာ ArrayList ရဲ႕ capacity က ၄ ခန္းယူထားေပးပါတယ္။ ကြၽန္ေတာ္တို႔ တန္ဖိုးထည့္ရင္းနဲ႔ ၄ခန္းျပည့္ျပီးလို႔ ေနာက္ထပ္ထပ္ထည့္တာနဲ႔ capacity က ၈ခန္းျဖစ္သြားမွာပါ။ ကိုယ္တကယ္ တန္ဖိုးထည့္ထားတဲ႔ အေရအတြက္ကိုေတာ့ count ဆိုတဲ႔ property ကေန ျပန္သိနိုင္ပါတယ္။ ArrayList က zero base index ျဖစ္ျပီးေတာ့ သူ႔ရဲ႕ index က integer type ပါ။ ArrayList ကလည္း object type လက္ခံတာျဖစ္တဲ႔ အတြက္ ကြၽန္ေတာ္တို႔ ၾကိဳက္တဲ႔ type ထည့္ေပးခြင့္ရွိပါတယ္။ example ေလးၾကည့္ရေအာင္။
using System;
using System.Collections;
class arraylistTest
{
static void Main()
{
object[] arr = new object[3];
arr[0] = 1;
arr[1] = 2.2;
arr[2] = "abcdefg";
ArrayList ar = new ArrayList();
ar.Add(1);
ar.Add(9.456);
ar.Add("ABC");
ar.Add('Z');
ar.Add(new arraylistTest());
for (int i = 0; i < ar.Count; i++)
{
Console.WriteLine("{0}\t( {1} )", ar[i], ar[i].GetType());
}
Console.WriteLine("\nActual Size of your Array : " + ar.Count);
Console.WriteLine("Total Capacity of your Array : " + ar.Capacity);
Console.Read();
}
}
Hashtable Class
Hashtable class ထဲမွာ key/value တြဲ႕ data ေတြ လက္ခံပါတယ္။ key/value အတြဲလိုက္ကို DictionaryEntry လို႔ေခၚပါေသးတယ္။ ArrayList မွာ ကြၽန္ေတာ္တို႔ index ကို integer type သံုးပါတယ္။ Hashtable မွာေတာ့ index ေထာက္ဖို႔အတြက္ key ကိုသံုးပါတယ္။ သူကလည္း object type ပါ၊ ဒါေၾကာင့္ ကြၽန္ေတာ္တို႔ ၾကိဳ႔က္တဲ႔ type နဲ႔ index ေထာက္လို႔ ရပါတယ္။ သိမ္းမယ့္ data ေတြကိုေတာ့ value အပိုင္းမွာ သိမ္းရပါတယ္။ သူလည္း object type ပါပဲ။ Hashtable ကလည္း ArrayList လိုပဲ size ကို dynamically increment လုပ္လို႔ ရပါတယ္။ Example ေလးၾကည့္ရေအာင္။
using System;
using System.Collections;
class arraylistTest
{
static void Main()
{
Hashtable ht = new Hashtable();
ht.Add("Name", "Sevenlamp");
ht.Add("Address", "Yangon");
ht.Add("Age", 28);
foreach (DictionaryEntry de in ht)
{
Console.WriteLine("{0}\t\t: \t {1} ", de.Key, de.Value);
}
Console.WriteLine("\nThere are {0} element/s in your Hashtable Array", ht.Count);
Console.Read();
}
}