频道栏目
首页 > 资讯 > C# > 正文

C#动态数组ArrayList常用的方法讲解

17-12-23        来源:[db:作者]  
收藏   我要投稿

动态数组

动态的增加和减少元素实现了ICollection和List和IEnumerable接口灵活的设置数组大小不安全的集合类型其元素为值类型时效率不高(装箱和拆箱导致效率不高)

ArrayList常用的方法

		//to create an ArrayList
		ArrayList arrayList = new ArrayList();


		//to add values
		arrayList.Add(32);
		arrayList.Add("Puma");
		arrayList.Add('a');
		//ArrayList can have different kinds of type of value

		//to output
		foreach (object obj in arrayList)
		{
			Console.Write(obj + " ");
		}
		Console.WriteLine();

		//show the capacity
		Console.WriteLine("the Capacity is:" + arrayList.Capacity);
		Console.WriteLine("Adding one more element");
		arrayList.Add(5);
		Console.WriteLine("Now the Capacity is:" + arrayList.Capacity);


		//count: gets the number of elements actually contained in ArrayList
		Console.WriteLine("The elements in the ArrayList are:" + arrayList.Count);


		//contains : Determines whether an element is in the ArrayList
		if(arrayList.Contains(32))
			Console.WriteLine("It exists!");
		else
			Console.WriteLine("It doesn'n exist");


		//Insert: Insert an element into ArrayList at the specified index
		arrayList.Insert(2,"real");
		foreach (object obj in arrayList)
		{
			Console.Write(obj + " ");
		}
		Console.WriteLine();


		//IndexOf:searches for the specified object and returns the zero-based index of the first occurrence within the entire ArrayList.
		Console.WriteLine(arrayList.IndexOf(32));


		//Remove:Removes the first occurrence of a specific object from the ArrayList
		arrayList.Remove(32);
		foreach (object obj in arrayList)
		{
			Console.Write(obj + " ");
		}
		Console.WriteLine();


		//Reverse:Reverses the order of the elements in the entire ArrayList
		arrayList.Reverse();
		foreach (object obj in arrayList)
		{
			Console.Write(obj + " ");
		}
		Console.WriteLine();


		//Sort:Sorts the elements in the entire ArrayList.
		arrayList.Add(3);
		arrayList.Add(42);
		arrayList.Remove("Puma");
		arrayList.Remove("real");
		arrayList.Remove('a');
		//before sorting
		foreach (object obj in arrayList)
		{
			Console.Write(obj + " ");
		}
		Console.WriteLine();
		arrayList.Sort();
		//after sorting
		foreach (object obj in arrayList)
		{
			Console.Write(obj + " ");
		}
		Console.WriteLine();
相关TAG标签
上一篇:简单可持久化数据结构详情
下一篇:Servlet&JSP前端代码报错:Failedtodecodedownloadedfont问题解决
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站