ArrayList,List,Hashtable,Dictionary的应用

ArrayList的应用(System.Collections)

ArrayList list = new ArrayList();

list.Add(new Student("aaa", 20));
list.Add(new Student("bbb", 21));
list.Add(new Student("ccc", 22));

for (int i = 0; i < list.Count; i++)
{
    Student stu = list[i] as Student;
    Console.WriteLine(string.Format("Name:{0}   Age:{1}", stu.Name, stu.Age));
}
foreach (Object obj in list)
{
    Student stu = obj as Student;
    Console.WriteLine(string.Format("Name:{0}   Age:{1}", stu.Name, stu.Age));
}

List<T>的应用(System.Collections.Generic)

List<Student> list = new List<Student>();

list.Add(new Student("aaa", 20));
list.Add(new Student("bbb", 21));
list.Add(new Student("ccc", 22));

for (int i = 0; i < list.Count; i++)
{
    Console.WriteLine(string.Format("Name:{0}   Age:{1}", list[i].Name, list[i].Age));
}
foreach (Student stu in list)
{
    Console.WriteLine(string.Format("Name:{0}   Age:{1}", stu.Name, stu.Age));
}

Hashtable的应用(System.Collections)

Hashtable hs = new Hashtable();

hs.Add("aaa", 20);
hs.Add("bbb", 21);
hs.Add("ccc", 22);

foreach (DictionaryEntry de in hs)
{
    Console.WriteLine(string.Format("Key:{0}    Value:{1}",de.Key,de.Value));
}

Dictionary<TKey, TValue>的应用(System.Collections.Generic)

Dictionary<string, int> dict = new Dictionary<string, int>();

dict.Add("aaa", 20);
dict.Add("bbb", 21);
dict.Add("ccc", 22);

foreach (KeyValuePair<string, int> kvp in dict)
{
    Console.WriteLine(string.Format("Key:{0}    Value:{1}", kvp.Key, kvp.Value));
}

说明:如果存储的元素是Object类型时,List<T>和Dictionary<TKey, TValue>会优于ArrayList和HashTable,因为在存储或检索值类型时ArrayList和HashTable经常要进行装箱和拆箱。

评论: 0 | 引用: 0 | 查看次数: 4153
发表评论
登录后再发表评论!