集合

集合

ArrayList

using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _0623ArrayList
{
    class Program
    {
        static void Main(string[] args)
        {

            //数组:长度不可变,类型单一
            //集合:长度任意改变,类型任意
            ArrayList list1 = new ArrayList();
            list1.Add('1');
            list1.Add(12);
            list1.Add(3.454);
            list1.Add(new int[] { 1, 2, 3, 4, 5 });
            Person p1 = new Person();
            list1.Add(p1);
            //添加集合用
            list1.AddRange(new int[] { 12, 3, 24, 4, 5 });
            //list1.Clear();清楚所有元素
            //list1.RemoveAt(0) 根据索引删除
            //list1.RemoveAt(0,3) 根据索引移除一定范围
            //list1.Insert(1,"在位置1出入"); 位置1插入一个元素
            //list1.InsertRange(1, new int[] { 232, 23, 23, 4 });在1的位置插入一个集合


            for (int i = 0; i < list1.Count; i++)
            {
                //Console.WriteLine(list1[i]);
                if (list1[i] is Person)
                {
                    ((Person)list1[i]).SayHello();
                }
                else if (list1[i] is int[])
                {
                    
                }
                else
                {
                    Console.WriteLine(list1[i]);
                }
            }

        }

        public class Person
        {
            public void SayHello()
            {
                Console.WriteLine("I am a person");

            }
        }
    }
}
  • 集合长度
    count 表示集合中实际包含的元素个数;
    capacity 表示集合中可以包含的元素个数;

Hashtable

  • 无序,key不能重复
using System;
using System.Collections;

namespace _0623Hashtable
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable ht = new Hashtable();
            ht.Add("name", "fxx");
            ht.Add("gender", "female");
            ht.Add("age", 18);
            
            //ht.Add("age", 20); key必须唯一
            //另外一种赋值,可以覆盖原有的key 
            ht["id"] = 123;
            Person p1 = new Person();
            if (!ht.ContainsKey("abc"))
            {
                ht["abc"] = p1;
            }
            //取值
            foreach (var item in ht.Keys)
            {
                if(ht[item] is Person)
                {
                    ((Person)ht[item]).SayHello();
                }
                else
                {
                    Console.WriteLine("key is {0}, value is {1}", item, ht[item]);

                }
            }
        }

        public class Person
        {
            public void SayHello()
            {
                Console.WriteLine("I am a person.");

            }
        }
    }
}

List范用类型

namespace _List泛型集合
{
    class Program
    {

        static void Main(string[] args)
        {
            List<int> list1 = new List<int>();
            {
                list1.Add(1);
                list1.Add(2);
                list1.Add(3);
                list1.Add(4);
                list1.AddRange(new int[] { 100, 200, 300 });
                //List泛型集合可以转为数组
                int[] nums = list1.ToArray();
                //数组转集合
                char[] chs1 = new char[] { 'c', 'b', 'a' };
                List<char> listchar = chs1.ToList();

            };
        }
    }
}
装箱,拆箱

装箱:将值类型转为引用类型
拆箱:将引用类型转为值类型
代码中要尽量避免装箱,拆箱;

  • 装箱例子
namespace _zx_cx
{
    class Program
    {

        static void Main(string[] args)
        {
            int a = 10;
            object b = a;//装箱,值给引用
            int c = (int)b; //拆箱,引用给值
            //所以值类型装箱了10000次
            ArrayList list1 = new ArrayList();//object类型
            for (int i = 0; i < 10000; i++)
            {
                list1.Add(i);//i是Int类型,转去引用,装箱
            }
        }
    }
}
  • 未发生拆箱装箱
namespace _zx_cx
{
    class Program
    {

        static void Main(string[] args)
        {
            //这里没有任何拆箱装箱,看两种类型是否发生拆箱装箱,要看两种类型是否存在继承关系,有继承关系才有可能发生
            string str1 = "123123";//string 引用类型
            int a = Convert.ToInt32(str1);//值类型

        }
    }
}
  • 发生了装箱
int  n =10;
IComparable i =n;//有继承关系,值到引用,所以发生了装箱

Dictionary

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace _Dictionary
{
    class Program
    {

        static void Main(string[] args)
        {
            Dictionary<int, string> dic1 = new Dictionary<int, string>();
            dic1.Add(1, "fxx");
            dic1.Add(2, "gjj");
            /*            foreach (var item in dic1.Keys)
                        {
                            Console.WriteLine("{0}-----{1}", item, dic1[item]);
                        }
            */
            foreach (KeyValuePair<int,string>kv in dic1)
            {
                Console.WriteLine("{0}----{1}", kv.Key, kv.Value);

            }

        }
    }
}
数组和集合的区别
  • 数组
    优点:由于他在内存中是连续的,所以他的索引和查询非常快
    缺点:长度是固定的,之后处理麻烦
namespace test2
{
    class JiangYou
    {
        static void Main(string[] args)
        {
            //ArrayList list1 = new ArrayList();
            //指定长度的数组
            string[] str1 = new string[2];
            str1[0] = "aaaa";
            str1[1] = "bbbb";
            str1[0] = "cccc";
            //未指定长度的数组
            int[] num1 = { 1, 2, 3, 4 };
            //num1[5] = 5;不能这么添加
            Console.WriteLine(num1);
        }
    }
}

  • ArrayList
    优点:大小和长度以及元素都是动态的且不用指定类型
    缺点:虽然解决了数组的固定长度问题,但是由于都是object类型,所以效率较低,造成类型不安全问题,带来很大的能耗
namespace test2
{
    class JiangYou
    {
        static void Main(string[] args)
        {
           
            int[] num1 = { 1, 2, 3, 4 };
            Person p1 = new Person();
            ArrayList list1 = new ArrayList();
            list1.Add("23123");
            list1.Add(num1);
            list1.Add(p1);
            Console.WriteLine(list1);
            foreach (var item in list1)
            {
                Console.WriteLine(item);

            }

        }

        public class Person
        {

        }
    }
}


  • List泛型
    泛型List是ArrayList类的泛型等效类,大部分用法和ArrayList相同,在声明时,需要声明List集合内数据的对象类型
    语法
List<T> ListOfT = new List<T>();

class Person
{
    private string name; //姓名
    private int age; //年龄
    //创建Person对象
    public Person(string name, int age)
    {
        this.name= name;
        this.age = age;
    }
}

//创建Person对象
Person p1 = new Person("张三", 23);
Person p2 = new Person("李四", 18);
Person p3 = new Person("王五", 41);
//创建类型为Person的对象集合
List<Person> persons = new List<Person>();
//将Person对象放入集合
persons.Add(p1);
persons.Add(p2);
persons.Add(p3);
//输出第2个人的姓名
Console.Write(persons[1].name);

  • 总结
  1. 数组的容量是固定的,我们只能一次获取或设置一个元素的值,而ArrayList或泛型List的容量可根据需要自动扩充、修改、删除或插入数据。
  2. 数组可以具有多个维度,而 ArrayList或泛型List始终只具有一个维度,但是我们可以轻松创建数组列表或列表的列表。
  3. 在决定使用泛型List还是使用ArrayList 类(两者具有类似的功能)时,记住泛型List类在大多数情况下执行得更好并且类型安全。如果对泛型List类的类型使用object类型时,则两个类的行为是完全相同的。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容