常规的数组存在局限性:
- 元素个数确定,只能创建已知大小。
- 元素类型必须相同。
- 只能通过索引访问数组。
在.NET框架中的常见集合类型有列表、队列、栈以及哈希表,即(Arraylist、Queue、stack、HastTable)。
ArrayList类
- 没有固定大小
- 默认大小为16个元素,当添加到第17个元素时会自动扩展到32个
- 可以显示的指定其容量
- 可以存储不同类型的元素,因为其中所有元素都是object基本类型
- 常用方法
- Add(object) 把一个对象添加到 ArrayList 的末尾 。
- Insert(index,object) 在指定位置插入一个对象 。
- Remove(object) 移除一个对象 。
- RemoveAt(index) 移除一个对象。
- Clear() 移除所有元素 。
- Sort 对ArrayList 中的元素进行排序 。
int i = 100;
double d = 999.88d;
string s = "Hello World";
DateTime time = DateTime.Now;
ArrayList myList = new ArrayList();
myList.Add(i);
myList.Add(d);
myList.Add(s);
myList.Add(time);
myList.insert(0, 200);
myList.RemoveAt(0);
- ! 在从列表中取对应元素时,需要用到类型转换,类似于装箱拆箱:
int s = (int) myList[ 0 ];
HashTable类
- 由一对(key , value) 类型的元素组成的集合
- 所有元素的 key 必须唯一
- key ->value 是一对一的映射,即根据key就可 以立刻在集合众找到所需元素
- 常用方法
- Add(key,value)
- 用key查找而不是索引查找,因此速度会很快
Hashtable ht = new Hashtable(); //创建HashTable
//增加对象
ht.Add("Beijing", "Sunny");
ht.Add("ShangHai", "Rainy");
ht.Add("Guandong", "Cloudy");
ht["Guandong"] = "Cloudy";//建立"Guandong"键值,Value取"Cloudy"。
//如果键值存在,value重新赋值
//若不存在,建立新对象,"Guandong"为键值,value为"Cloudy"。
//读对象
string bjWeather = (string)ht["Beijing"];
//读取时需要装箱拆箱(类型转换)
//其他用法
//ContainsKey方法
bool keyFound;
if(ht.ContainsKey(“Beijing”))
keyFound=true;
else
keyFound=false;
//列举HashTable中的Keys
foreach(string key in ht.Keys)
{
MessageBox.Show(key);
}
//列举HashTable中的Values
foreach(string value in ht.Values)
{
MessageBox.Show(value);
}
//列举HashTable中的Keys和Values
foreach(DictionaryEntry de in ht)
{
MessageBox.Show(de.Key + " " + de.Values);
}
泛型集合
- 泛型,顾名思义就是泛泛的类型。即没有确定的类型. 那么没有确定类型怎么使用呢?
- 实际上,使用的时候规定类型即可了。集合,就是一种处理多个数据类型的类。而且一般你会在多个应用程序中使用同一个集合的多种不同的形式。你不须要每次依据草稿建立集合,而是使用泛型建立一个泛型类原型(prototype)。
- 在使用的时候,依据须要处理的数据类型。将List< T >尖括号里的T换成相应的类型,并创建相应的实例就能够使用了。
- 编译时需要检查类型约束,指定数据类型。
- 不需要装箱拆箱操作。
- 命名空间: System.Collections.Generic
- List< T >,Dictionary<K,V>
- < T >代表元素类型
- <K,V>同代表类型,K为键值类型,V为value类型
List< T >
- List< Student> students = new List< Student>();
- 利用List< Student>存储班级集合,这种指定方式类似于vector
- 访问方式与ArrayList相同
Student stu1 = students[2]; //使用索引访问,无需类型转换
stu1.SayHi(); //调用方法
Students.RemoveAt(0); //利用索引删除
//List<Student>方式
foreach (Student stu in students)
{
Console.WriteLine(stu.Name);//调用成员
}
- 使用 .Sort()排序的时候遵循一定的规则
- +++++++++++++++++++++++++++++++++
- +++++++++++++++++++++++++++++++++//补充
前面说到了类似于ArrayList的List,下面还有类似于哈希表Key、Value形式的泛型集合。
Dictionary<K,V>
- Dictionary<string,Student> students = new Dictionary<string,Student>();
- <K,V>约束集合中元素类型
- 编译时检查类型约束
- 无需装箱拆箱操作
students.Add(scofield.Name, scofield);
…
student stu2 = students["周杰"];
…
students.Remove("周杰"); //索引都是通过**键值**来完成!!!
//Dictionary<string, Student> 方式
foreach (Student student in students.Values)
{
Console.WriteLine(student.Name);
}