C# 集合类 :(Array、 Arraylist、List、Hashtable、Dictionary、Stack、Queue)
来源:互联网 发布:骇战网络暴力 编辑:程序博客网 时间:2024/06/05 19:29
我们用的比较多的非泛型集合类主要有 ArrayList类 和 HashTable类。我们经常用HashTable 来存储将要写入到数据库或者返回的信息,在这之间要不断的进行类型的转化,增加了系统装箱和拆箱的负担,14:31:45,例如我们需要在电子商务网站中存储用户的购物车信息(商品名,对应的商品个数)时,完全可以用 Dictionary
int[] intArray1; //初始化已声明的一维数组 intArray1 = new int[3]; intArray1 = new int[3]{1,2,3}; intArray1 = new int[]{1,2,3};
- ArrayList类对象被设计成为一个动态数组类型,其容量会随着需要而适当的扩充
方法
1:Add()向数组中添加一个元素,
2:Remove()删除数组中的一个元素
3:RemoveAt(int i)删除数组中索引值为i的元素
4:Reverse()反转数组的元素
5:Sort()以从小到大的顺序排列数组的元素
6:Clone()复制一个数组
using System; using System.Collections.Generic; using System.Text; using System.Collections; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { ArrayList al = new ArrayList(); al.Add(100);//单个添加 foreach (int number in new int[6] { 9, 3, 7, 2, 4, 8 }) { al.Add(number);//集体添加方法一//清清月儿 } int[] number2 = new int[2] { 11,12 }; al.AddRange(number2);//集体添加方法二 al.Remove(3);//移除值为3的 al.RemoveAt(3);//移除第3个 ArrayList al2 = new ArrayList(al.GetRange(1, 3));//新ArrayList只取旧ArrayList一部份 Console.WriteLine("遍历方法一:"); foreach (int i in al)//不要强制转换 { Console.WriteLine(i);//遍历方法一 } Console.WriteLine("遍历方法二:"); for (int i = 0; i != al2.Count; i++)//数组是length { int number = (int)al2[i];//一定要强制转换 Console.WriteLine(number);//遍历方法二 } } } }
- List
可通过索引访问的对象的强类型列表。提供用于对列表进行搜索、排序和操作的方法,在决定使用 List 还是使用 ArrayList 类(两者具有类似的功能)时,记住 List 类在大多数情况下执行得更好并且是类型安全的。如果对 List 类的类型 T 使用引用类型,则两个类的行为是完全相同的。但是,如果对类型 T 使用值类型,则需要考虑实现和装箱问题。
如果对类型 T 使用值类型,则编译器将特别针对该值类型生成 List 类的实现。这意味着不必对 List 对象的列表元素进行装箱就可以使用该元素,并且在创建大约 500 个列表元素之后,不对列表元素装箱所节省的内存将大于生成该类实现所使用的内存。
常用的方法
方法说明
Add:将指定的键和值添加到字典中。
Clear :从 Dictionary中移除所有的键和值。
ContainsKey :确定 Dictionary是否包含指定的键。
ContainsValue :确定 Dictionary是否包含特定值。
Equals:已重载。 确定两个 Object实例是否相等。 (从 Object继承。)
GetEnumerator:返回循环访问 Dictionary的枚举数。
GetHashCode :用作特定类型的哈希函数。GetHashCode适合在哈希算法和数据结构(如哈希表)中使用。 (从 Object继承。)
GetObjectData :实现 System.Runtime.Serialization.ISerializable接口,并返回序列化 Dictionary实例所需的数据。
GetType :获取当前实例的 Type。 (从 Object继承。)
OnDeserialization:实现 System.Runtime.Serialization.ISerializable接口,并在完成反序列化之后引发反序列化事件。
ReferenceEquals :确定指定的 Object实例是否是相同的实例。 (从 Object继承。)
Remove :从 Dictionary中移除所指定的键的值。
ToString :返回表示当前 Object的 String。 (从 Object继承。)
TryGetValue :获取与指定的键相关联的值。
//声明一个List对象,只加入string参数 List<string> names = new List<string>(); names.Add("乔峰"); names.Add("欧阳峰"); names.Add("马蜂"); //遍历List foreach (string name in names) { Console.WriteLine(name); } //向List中插入元素 names.Insert(2, "张三峰"); //移除指定元素 names.Remove("马蜂");
- Dictionary
表示键和值的集合。Dictionary遍历输出的顺序,就是加入的顺序,这点与Hashtable不同 Dictionary<string, string> myDic = new Dictionary<string, string>(); myDic.Add("aaa", "111"); myDic.Add("bbb", "222"); myDic.Add("ccc", "333"); myDic.Add("ddd", "444"); //如果添加已经存在的键,add方法会抛出异常 try { myDic.Add("ddd","ddd"); } catch (ArgumentException ex) { Console.WriteLine("此键已经存在:" + ex.Message); } //解决add()异常的方法是用ContainsKey()方法来判断键是否存在 if (!myDic.ContainsKey("ddd")) { myDic.Add("ddd", "ddd"); } else { Console.WriteLine("此键已经存在:"); } //而使用索引器来负值时,如果建已经存在,就会修改已有的键的键值,而不会抛出异常 myDic ["ddd"]="ddd"; myDic["eee"] = "555"; //使用索引器来取值时,如果键不存在就会引发异常 try { Console.WriteLine("不存在的键""fff""的键值为:" + myDic["fff"]); } catch (KeyNotFoundException ex) { Console.WriteLine("没有找到键引发异常:" + ex.Message); } //解决上面的异常的方法是使用ContarnsKey() 来判断时候存在键,如果经常要取健值得化最好用 TryGetValue方法来获取集合中的对应键值 string value = ""; if (myDic.TryGetValue("fff", out value)) { Console.WriteLine("不存在的键""fff""的键值为:" + value ); } else { Console.WriteLine("没有找到对应键的键值"); } //下面用foreach 来遍历键值对 //泛型结构体 用来存储健值对 foreach (KeyValuePair<string, string> kvp in myDic) { Console.WriteLine("key={0},value={1}", kvp.Key, kvp.Value); } //获取值得集合 foreach (string s in myDic.Values) { Console.WriteLine("value={0}", s); } //获取值得另一种方式 Dictionary<string, string>.ValueCollection values = myDic.Values; foreach (string s in values) { Console.WriteLine("value={0}", s); }
- SortedList类
与哈希表类似,区别在于SortedList中的Key数组排好序的
//SortedList System.Collections.SortedList list=new System.Collections.SortedList(); list.Add("key2",2); list.Add("key1",1); for(int i=0;i<list.Count;i++) { System.Console.WriteLine(list.GetKey(i)); }
6.Hashtable类
哈希表,名-值对。类似于字典(比数组更强大)。哈希表是经过优化的,访问下标的对象先散列过。如果以任意类型键值访问其中元素会快于其他集合。
GetHashCode()方法返回一个int型数据,使用这个键的值生成该int型数据。哈希表获取这个值最后返回一个索引,表示带有给定散列的数据项在字典中存储的位置。
Hashtable 和 Dictionary
//Hashtable sample System.Collections.Hashtable ht = new System.Collections.Hashtable(); //--Be careful: Keys can't be duplicated, and can't be null---- ht.Add(1, "apple"); ht.Add(2, "banana"); ht.Add(3, "orange"); //Modify item value: if(ht.ContainsKey(1)) ht[1] = "appleBad"; //The following code will return null oValue, no exception object oValue = ht[5]; //traversal 1: foreach (DictionaryEntry de in ht) { Console.WriteLine(de.Key); Console.WriteLine(de.Value); } //traversal 2: System.Collections.IDictionaryEnumerator d = ht.GetEnumerator(); while (d.MoveNext()) { Console.WriteLine("key:{0} value:{1}", d.Entry.Key, d.Entry.Value); } //Clear items ht.Clear();Dictionary和HashTable内部实现差不多,但前者无需装箱拆箱操作,效率略高一点。 //Dictionary sample System.Collections.Generic.Dictionary<int, string> fruits = new System.Collections.Generic.Dictionary<int, string>(); fruits.Add(1, "apple"); fruits.Add(2, "banana"); fruits.Add(3, "orange"); foreach (int i in fruits.Keys) { Console.WriteLine("key:{0} value:{1}", i, fruits); } if (fruits.ContainsKey(1)) { Console.WriteLine("contain this key."); }
HashTable是经过优化的,访问下标的对象先散列过,所以内部是无序散列的,保证了高效率,也就是说,其输出不是按照开始加入的顺序,而Dictionary遍历输出的顺序,就是加入的顺序,这点与Hashtable不同。如果一定要排序HashTable输出,只能自己实现:
//Hashtable sorting System.Collections.ArrayList akeys = new System.Collections.ArrayList(ht.Keys); //from Hashtable akeys.Sort(); //Sort by leading letter foreach (string skey in akeys) { Console.Write(skey + ":"); Console.WriteLine(ht[skey]); }
HashTable与线程安全:
为了保证在多线程的情况下的线程同步访问安全,微软提供了自动线程同步的HashTable:
如果 HashTable要允许并发读但只能一个线程写, 要这么创建 HashTable实例:
//Thread safe HashTableSystem.Collections.Hashtable htSyn = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable());
这样, 如果有多个线程并发的企图写HashTable里面的 item, 则同一时刻只能有一个线程写, 其余阻塞; 对读的线程则不受影响。
另外一种方法就是使用lock语句,但要lock的不是HashTable,而是其SyncRoot;虽然不推荐这种方法,但效果一样的,因为源代码就是这样实现的:
//Thread safeprivate static System.Collections.Hashtable htCache = new System.Collections.Hashtable ();public static void AccessCache (){ lock ( htCache.SyncRoot ) { htCache.Add ( "key", "value" ); //Be careful: don't use foreach to operation on the whole collection //Otherwise the collection won't be locked correctly even though indicated locked //--by MSDN }}//Is equivalent to 等同于 (lock is equivalent to Monitor.Enter and Exit()public static void AccessCache (){ System.Threading.Monitor.Enter ( htCache.SyncRoot ); try { /* critical section */ htCache.Add ( "key", "value" ); //Be careful: don't use foreach to operation on the whole collection //Otherwise the collection won't be locked correctly even though indicated locked //--by MSDN } finally { System.Threading.Monitor.Exit ( htCache.SyncRoot ); }}
- Stack类
栈,后进先出。push方法入栈,pop方法出栈。
System.Collections.Stack stack=new System.Collections.Stack(); stack.Push(1); stack.Push(2); System.Console.WriteLine(stack.Peek()); while(stack.Count>0) { System.Console.WriteLine(stack.Pop()); }
8.Queue类
队列,先进先出。enqueue方法入队列,dequeue方法出队列。
System.Collections.Queue queue=new System.Collections.Queue(); queue.Enqueue(1); queue.Enqueue(2); System.Console.WriteLine(queue.Peek()); while(queue.Count>0) { System.Console.WriteLine(queue.Dequeue()); }
原文请点击此处
- C# 集合类 Array Arraylist List Hashtable Dictionary Stack Queue
- C# 集合类 Array Arraylist List Hashtable Dictionary Stack Queue
- C# 集合类 Array, Arraylist, List, Hashtable, Dictionary, Stack, Queue
- C# 集合类 Array Arraylist List Hashtable Dictionary Stack Queue
- C# 集合类 Array Arraylist List Hashtable Dictionary Stack Queue
- C# 集合类 Array Arraylist List Hashtable Dictionary Stack Queue
- C# 集合类 Array Arraylist List Hashtable Dictionary Stack Queue
- C# 集合类 Array Arraylist List Hashtable Dictionary Stack Queue
- C# 集合类 Array Arraylist List Hashtable Dictionary Stack Queue
- C# 集合类 Array Arraylist List Hashtable Dictionary Stack Queue
- [c#基础知识] C# 集合类 :(Array、 Arraylist、List、Hashtable、Dictionary、Stack、Queue)
- C# 集合类 :(Array、 Arraylist、List、Hashtable、Dictionary、Stack、Queue)
- C# 集合类 :(Array、 Arraylist、List、Hashtable、Dictionary、Stack、Queue)
- C# 集合类 :(Array、 Arraylist、List、Hashtable、Dictionary、Stack、Queue)
- C# 集合类 :(Array、 Arraylist、List、Hashtable、Dictionary、Stack、Queue)
- C# 集合类 :(Array、 Arraylist、List、Hashtable、Dictionary、Stack、Queue)
- C# 集合类 :(Array、 Arraylist、List、Hashtable、Dictionary、Stack、Queue)
- C# 集合类 :(Array、 Arraylist、List、Hashtable、Dictionary、Stack、Queue)
- Android 动画技术
- IOS修改titleView的字体颜色
- 结构体在内存中的存储方式
- 小球弹跳:UI2-2
- dark认为比较好比较全的java反射详解示例
- C# 集合类 :(Array、 Arraylist、List、Hashtable、Dictionary、Stack、Queue)
- Android中单击空白区域隐藏键盘
- boost库timed_wait、notify_one配合使用
- onTouch,onClick,onLongClick事件发生先后顺序和关联
- 在ECLIPSE导入项目后提示::具有不受限制的类路径容器:“JRE 系统库 [JVM 1.6.0]”
- 理解A*寻路算法具体过程
- js框架jquery实现幸运大转盘抽奖程序代码,兼容多种浏览器
- 打靶问题
- java中this的用法