2014-12-18 集合

//首先定义一个新的array类

class ArrayListjihe
    {
        static void Main(string[] args)
        {
            ArrayList arr = new ArrayList();
            arr.Add(3);   
            arr.Add("hello");
            //通过添加元素的先后顺序生成从0开始的索引,通过索引读取数据
            Console.WriteLine(arr[0]);
            Console.WriteLine(arr[2]);
        }
    }

 //ArrayList必须引用 using System.Collections;

arr.Insert(1,17)  //向集合1的位置插入17这个数字

int[] shuzu=new int[3]{6,7,8};

arr.InsertRange(1,shuzu);   //拆解数组,向1的位置插入数组

arr.AddRange(shuzu);  //拆解数组,在集合后面的位置追加数组

 

//显示集合中的所有内容

            foreach (object o in arr)
            {
                Console.WriteLine(o.ToString());
            }

//添加数组个体
            arr.Add(shuzu);
            int [] newshu=(int[]arr[3]);
            foreach(int a in newshu)
            {
                Console.WriteLine(a);
            }

 

//移除数据
            arr.Remove("hello");  //移除第一个位置的hello
            arr.RemoveAt(3);   //移除指定位置的数据

 

//集合的排序功能
            ArrayList arr = new ArrayList();
            for (int i = 0; i < 5; i++)
            {
                arr.Add(int.Parse(Console.ReadLine()));
            }
            arr.Sort();  //升序排序
            arr.Reverse();  //翻转集合

            foreach (int a in arr)
            {
                Console.WriteLine(a);
            }

Console.WriteLine(arr.Count);  //返回集合中元素的个数
Console.WriteLine(arr.IndexOf(14));  //返回集合中第一个14的位置
Console.WriteLine(arr.LastIndexOf(14));  //返回集合中最后一个14的位置

posted @ 2014-12-19 11:55  雪山飞驴  阅读(109)  评论(0编辑  收藏  举报