ArrayList
ArrayList是万物之父object类型的数组,就是可以存储任意类型的动态数组,但同时存在装箱和拆箱,所以ArrayList少用
需引入命名空间using System.Collections;
最重要就是它的增删改查的一些函数了:
static void Main(string[] args)
{
ArrayList array = new ArrayList();
array.Add(1);
array.Add("s");
array.Add(new object());
ArrayList array2 = new ArrayList();
array2.Add("2");
array2.Add("s2");
array.AddRange(array2);//addRange加整个arraylist
//Console.WriteLine(array[2]);
array.Insert(1, "123");//指定位置插入元素
Console.WriteLine(array[1]);
//移除指定元素,从头开始
array.Remove(1);
//移除指定位置的元素
array.RemoveAt(2);
//Contains查找元素是否存在
if(array.Contains("s"))
{
Console.WriteLine("存在s");
}
array.Add(true);
//indexOf从头开始找指定元素,有则返回位置,没有返回-1
int index = array.IndexOf(true);
Console.WriteLine(index);//3
int tmp = array.IndexOf(false);
Console.WriteLine(tmp);//-1
//LastIndexOf从尾开始找
index = array.LastIndexOf(true);
//改
array[0] = 1;
//遍历
//获取list长度
Console.WriteLine(array.Count);//5
//获取list容量
Console.WriteLine(array.Capacity);//8
for (int i = 0; i < array.Count;i++)
{
Console.WriteLine(array[i]);
}
//迭代器遍历
foreach (object it in array)
{
Console.WriteLine(it);
}
Console.ReadKey();
}
List
2.List是一个可变类型的泛型数组,相当于c++的vector
可以自己指定类型,不存在装箱和拆箱问题,所以使用频率比ArrayList高很多,且用法也一样
需引入命名空间using System.Collections.Generic;
List<int> list = new List<int>();
HashTable
Hashtable就是哈希表,键值对的形式
static void Main(string[] args)
{
Hashtable hash = new Hashtable();
//加
hash.Add(1, "123");
hash.Add("abc", 1.2f);
hash.Add(true, 1);
//删除对应键的值
hash.Remove(1);
//查,没有返回空
Console.WriteLine(hash[true]);
if(hash.Contains("abc"))
{
Console.WriteLine("存在键为abc");
}
if (hash.ContainsKey("abc"))
{
Console.WriteLine("存在键为abc");
}
if (hash.ContainsValue(1))
{
Console.WriteLine("存在值为1的键值对");
}
//遍历哈希表的键
foreach(object it in hash.Keys)
{
Console.WriteLine("键:"+it+"值:"+hash[it]);
}
//键值一起遍历
foreach(DictionaryEntry it in hash)
{
Console.WriteLine("键:" + it.Key + "值:" + it.Value);
}
Console.ReadKey();
}
Dictionary
Dictionary就是泛型的Hashtable
同样需引入命名空间using System.Collections.Generic;
只给出与Hashtable不同的一些东西,其他用法一致
Dictionary<int, string> dic = new Dictionary<int, string>();
dic.Add(1, "abc");
//键值一起遍历
foreach(KeyValuePair<int,string> it in dic)
{
Console.WriteLine("键:" + it.Key + " 值:" + it.Value);
}