C#:浅谈Arraylist与List、Hashtable与Dictionary的区别

前言:本来今天是想总结有关索引器的概念,无奈中间学习的时候,发现自己对List、Arraylist的理解不够到位,因此回去好好复习了一下,这一复习不要紧,自己发现了这几个知识点自己记的有些混乱,因此整理了一下,我们来说说这几个用法之间的异同。

1.ArrayList:集合,是数组的加强版:它是各种类型的数组。

语法:

using System;
using System.Collections;//需手动导入命名空间

namespace ConsoleApp7
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList a = new ArrayList();
            a.Add(20);
            a.Add("小乾");
            a.Add('女');
            a.Add(true);
            a.Add(3.1m);
            a.Add(nums);
        }
    }

我们能看到,arraylist能加入各种格式的内容,比数组的功能要强大很多。

2.Hashtable:哈希表,通过键值对的方式存值。

语法:

using System;
using System.Collections;//需手动添加命名空间

namespace ConsoleApp12
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable ht = new Hashtable();
            //哈希表以键值对的形式存值 

            //ht.Add(key,value);   key---键,value---值

            ht.Add("小乾", "111");
            ht.Add("小涛", 222);
            ht.Add(444, "飞机");
            ht.Add("333","汽车");
            ht.Add(1, "超任");
        }
    }
}

对于使用的方法我不多讲解,在我之前的博客有所提及。C#:哈希表

3.List:List<T>,放入声明好的同类型数据。

语法:

using System;
using System.Collections.Generic;//需要手动添加命名空间

namespace ConsoleApp16
{
    class Program
    {
        static void Main(string[] args)
        {
            //放整型数据
            List<int> list = new List<int>();
            list.Add(2);
            int[] nums = new int[] { 1, 2, 3, 4, 5 };
            list.AddRange(nums);//放数组

            //放字符串
            List<string> list1 = new List<string>();
            list1.Add("哈哈,小扬又变帅了");
        }
    }
}

我们可以看到,List中添加的数据同样需要数据类型的限制,这就是它和ArrayList的区别。

4.Dictionary:字典,同样通过键值对的方式写入数据,但有数据类型限制。

语法:

using System;
using System.Collections.Generic;//需要手动添加命名空间
using System.Linq;
using System.Text;

namespace ConsoleApp18
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int,int> dic = new Dictionary<int, int>();

            dic.Add(1, 1);
            dic.Add(2, 2);
            dic.Add(3, 3);
        }
    }
}

字典与哈希表的区别在于,字典也需要声明好要输入的键值对的数据类型,而不是像哈希表一样可以添加任意类型的键值对。

先简单的探讨这么多,希望大家能区分开这几个的不同点。

猜你喜欢

转载自blog.csdn.net/Marshallren/article/details/86661216