zoukankan      html  css  js  c++  java
  • c#数组与集合

    数组在内存中是连续存储的,所以索引速度很快,增删改元素也很简单。但是数组是分配在一块连续的数据空间上的,因此分配空间的同时就必须确定好空间的大小,空间的连续也导致增删改及存储元素的效率很低。如在数组中添加元素,就需在内存空间中“腾出”一块地方,别的元素再往后“cuan”位置。还有在声明数组时,必须指定数组长度,长也不好短也不行,怎么办?于是集合出现了。

    ArrayList示例:

    static void Main(string[] args)
            {
                ArrayList list = new ArrayList();
                list.Add(true);
                list.Add(1);
                list.Add("张三");
                list.AddRange(new int[] { 1, 2, 3, 4, 5, 6, 7, 8 });
                list.AddRange(list);
                //list.Clear();//清除
                //list.Reverse();//反转
                //list.InsertRange(0, new string[] {"李四"});//指定位置插入集合
                if (list.Contains("张三"))//判断包含指定元素
                {
                    Console.WriteLine("已经有这个屌丝啦~");
                }
                for (int i = 0; i < list.Count; i++)
                {
                    Console.WriteLine(list[i]);
                }
                Console.ReadKey();
            }

    List<>示例:

    static void Main(string[] args)
            {
                List<int> lt = new List<int>();
                lt.Add(1);
                lt.Add(2);
                lt.Add(3);
                lt.AddRange(new int[] { 4, 5, 6, 7, 8, 9 });
                for (int i = 0; i < lt.Count; i++)
                {
                    Console.WriteLine(lt[i]);
                }
                Console.ReadKey();
            }

    Hashtable示例:

    static void Main(string[] args)
            {
                Hashtable hash = new Hashtable();
                hash.Add(1, "张三");
                hash.Add(2, true);
                hash.Add(false, "错误的~");
                foreach (var h in hash.Keys)
                {
                    Console.WriteLine("键是{0},值是{1}", h, hash[h]);
                }
                Console.ReadKey();
            }

    Dictionary示例:

     static void Main(string[] args)
            {
                Dictionary<int, string> dir = new Dictionary<int, string>();
                dir.Add(1, "张三");
                dir.Add(2, "李四");
                dir[1] = "干掉你";
                foreach (KeyValuePair<int, string> kv in dir)
                {
                    Console.WriteLine("键是{0},值是{1}", kv.Key, kv.Value);
                }
                Console.ReadKey();
            }

    小结:

    ArrayList集合对数据类型没有要求,是因为ArrayList集合中存储的数据类型默为object类型,其它类型与object类型进行转换时就会发生“拆箱装箱”操作,而List集合在声明集合时就确定了数据类型,所以List集合与ArrayList集合相比是相对安全的哦。键值对集合与字典集合同理。

  • 相关阅读:
    leetcode 29-> Divide Two Integers without using multiplication, division and mod operator
    ros topic 发布一次可能会接收不到数据
    python中的print()、str()和repr()的区别
    python 部分函数
    uiautomatorviewer错误 unable toconnect to adb
    pyqt 不规则形状窗口显示
    appium 计算器demo
    Spring 3.0 注解注入详解
    Spring Autowire自动装配
    restful 学习地址
  • 原文地址:https://www.cnblogs.com/huangxuQaQ/p/10732121.html
Copyright © 2011-2022 走看看