美文网首页
Lession11集合和泛型

Lession11集合和泛型

作者: 任人渐疏_Must | 来源:发表于2021-06-15 08:11 被阅读0次

创建ArrayList

class Program
    {
        static void Main(string[] args)
        {
            //创建一个集合
            ArrayList list = new ArrayList();
            //集合:很多数据的集合
            //数组:长度不可变,类型单一
            //集合的好处:长度可以任意改变  类型随便
            list.Add(1);
            list.Add(3.14);
            list.Add(true);
            list.Add("张三");
            list.Add('男');
            list.Add(1000M);
          //  list.Add(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });

            for (int i = 0; i <list.Count; i++)
            {
                if(list[i] is int[])
                {
                    for (int j = 0; j < ((int[])list[i]).Length; j++)
                    {
                        Console.WriteLine(((int[])list[i])[j]);
                    }
                }
                else
                {
                    Console.WriteLine(list[i]);
                }
               
            }

            Console.ReadKey();
        }
    }


ArrayList的长度

/*
     * 每次集合中实际包含的元素个数(Count)超过了可以包含的元素的个数(Capacity)的时候,
     * 集合就会向内存中申请开辟一倍的空间,来保证集合的长度一直够用
     * 
     */
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList list = new ArrayList();
            list.Add(1);
            list.Add(1);
            list.Add(1);
            list.Add(1);
            list.Add(1);
            list.Add(1);
            list.Add(1);
            list.Add(1);
            list.Add(1);
            Console.WriteLine(list.Count);
            Console.WriteLine(list.Capacity);
            Console.ReadKey();
        }
    }

ArrayList的方法

 class Program
    {
        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, 9 });
            //list.AddRange(list);
            //清空所有元素
            // list.Clear();
            //删除单个元素
            //list.Remove(true);//写谁删除谁
            //list.RemoveAt(0);//根据下标删除元素
            //list.RemoveRange(0,3);//根据下标去移除一定范围的元素
            //list.Sort();//升序排序
            //list.Reverse();//反转
            //list.Insert(1, "插入的"); //在指定的位置插入一个元素
            //list.InsertRange(0,new string[]{"李四","王五"});//在指定的位置插入一个集合
            bool b = list.Contains(1);//判断是否包含某个指定的元素
            if (!list.Contains("马六"))
            {
                list.Add("马六");
            }
            else
            {
                Console.WriteLine("已经有这个屌丝了");
            }

            for (int i = 0; i < list.Count; i++)
            {
                Console.WriteLine(list[i]);
            }
            Console.ReadKey();
        }
    }


ArrayList存放对象

 /*
     * 使用ArrayList集合:
     * 1.引入System.Collections命名空间
     * 2.实例化ArrayList对象
     * 
     * ArrayList的方法:
     * Add():添加
     * Remove()删除
     * 
     */
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList students = new ArrayList();  //实例化对象
            ArrayList teachers = new ArrayList(5);//可以指定长度

            Student stu1 = new Student(1,"张三",18,Gender.男);
            Student stu2 = new Student(2, "李四", 19, Gender.女);
            Student stu3 = new Student(3, "王五", 20, Gender.男);
            students.Add(stu1);
            students.Add(stu2);
            students.Add(stu3);
            //按照索引下标取出对象
           Student s1 = (Student)students[0];
           s1.SayHi();
           Console.ReadKey();
        }
    }

    public class Student
    {
        public Student(int StuId,string Name,int Age,Gender Gender)
        {
            this.stuId = StuId;
            this.name = Name;
            this.age = Age;
            this.gender = Gender;

        }
        public int stuId;
        public string name;
        public int age;
        public Gender gender;

        public void SayHi()
        {
            Console.WriteLine("大家好,我是{0},今年{1}岁,很开心认识大家",this.name,this.age);
        }

    }

    public enum Gender
    {
        男,
        女

    }


ArrayList小练习

 class Program
    {
        static void Main(string[] args)
        {
            //创建一个集合,里面添加一些数字,求平均值与和,最大值,最小值
            ArrayList list = new ArrayList();
            list.AddRange(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
            int sum = 0;
            int max = (int)list[0];
            for (int i = 0; i < list.Count; i++)
            {
                if ((int)list[i] > max)
                {
                    max = (int)list[i];
                }
                //父类中装有子类对象,所以,父类可以强制转换为子类对象
                sum += (int)list[i];
            }
            Console.WriteLine(sum);
            Console.WriteLine(sum / list.Count);
            Console.WriteLine(max);
            Console.WriteLine("---------------------------------");

            //写一个长度为10的集合,要求在里面随机存放10个数字(0-9),但要求所有数字不能重复
            ArrayList list2 = new ArrayList();
            Random rd = new Random();
            for (int i = 0; i < 10; i++)
            {
                int rNumber = rd.Next(0, 10);
                if (!list2.Contains(rNumber))
                {
                    list2.Add(rNumber);
                }
                else
                {
                    //一旦产生了重复的随机数,这次循环就不算数了
                    i--;
                }

            }

            for (int i = 0; i < list2.Count; i++)
            {
                Console.WriteLine(list2[i]);
            }

            Console.ReadKey();
        }
    }

HashTable创建

 /*
    * HashTable 健值对集合    字典    张         zhang->张
    * 在键值对集合当中,我们是根据键去找值的
    * 健值对对象[键]=值;
    * ** 健值对集合中,键必须是唯一的,而值是可以重复的
    */
    class Program
    {
        static void Main(string[] args)
        {
            //创建了一个键值对集合对象
            Hashtable ht = new Hashtable();
            ht.Add(1, "张三");
            ht.Add(2, true);
            ht.Add(3, '五');
            ht.Add(false, "错误的");


            ht[6] = "新来的"; //这也是一种添加数据的方式
            ht[1] = "把张三干掉";

            //abc--->cba

            if (!ht.ContainsKey("abc"))
            {
                ht.Add("abc", "cba");
            }
            else
            {
                Console.WriteLine("已经包含了这个键");
            }

           // ht.Clear();//清除健值集合
          //  ht.Remove(3);//根据键去移除里面的元素

            foreach (var item in ht.Keys)
            {
                Console.WriteLine("键是:{0}================>值是:{1}", item, ht[item]);
            }

            //在键值对集合中,是根据键去找值的
            //Console.WriteLine(ht[1]);
            //Console.WriteLine(ht[2]);
            //Console.WriteLine(ht[3]);
            //Console.WriteLine(ht[false]);


            //for (int i = 0; i < ht.Count; i++)
            //{
            //    Console.WriteLine(ht[i]);
            //}
            Console.ReadKey();
        }
    }

HashTable练习

 class Program
    {
        static void Main(string[] args)
        {
           Hashtable ht = new Hashtable();
            while (true)
            {
                // Console.BackgroundColor = ConsoleColor.Red;
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("==============请选择操作================");
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("    1.添加联系人    2.查找");
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("=======================================");
                Console.Write("请输入你的选择:");
                string f = Console.ReadLine();
                switch (f)
                {
                    case "1":
                        Console.WriteLine("请输入联系人名字:");
                        string name = Console.ReadLine();
                        Console.WriteLine("请输入联系人电话:");
                        string tel = Console.ReadLine();
                        if (ht.ContainsKey(name))
                        {
                            Console.WriteLine("该联系人已经存在", "错误");
                            return;
                        }
                        ht.Add(name, tel);
                        Console.WriteLine($"*******共有{ht.Count}位联系人************");
                        break;
                    case "2":
                        Console.Write("请输入要查找的联系人姓名:");
                        string nameFind = Console.ReadLine();
                        object telFind = ht[nameFind];
                        //用联系人名称作为索引来获得对应的联系人电话
                        if (telFind == null)
                        {
                            Console.WriteLine("该联系人不存在", "错误");
                        }
                        else
                        {
                            Console.WriteLine($"你所查找的联系人电话是:{telFind}");
                        }
                        break;
                }
            }

        }
    }


List泛型集合

 /*
     * 泛型集合就是明确指定了要放入集合的对象是何种类型的集合
     * 
     */
    class Program
    {
        static void Main(string[] args)
        {
            //创建泛型集合对象
            List<int> list = new List<int>();
            list.Add(1);
            list.Add(2);
            list.Add(3);
            list.AddRange(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
            list.AddRange(list);
            

            //List泛型集合可以转换成数组
            int[] nums = list.ToArray();

            List<string> listStr = new List<string>();
            string[] strs = listStr.ToArray();

            for (int i = 0; i < list.Count; i++)
            {
                Console.WriteLine(list[i]);
            }
            Console.ReadKey();
        }
    }

List泛型集合练习

class Program
    {
        static void Main(string[] args)
        {
            Student s1 = new Student(1, "张三");
            Student s2 = new Student(2, "李四");
            Student s3 = new Student(3, "王五");
            // List<Student> students = new List<Student> { s1, s2, s3,  1 };
            //集合初始化器
            List<Student> students = new List<Student> { s1, s2, s3};
            
            //foreach (var item in students)
            //{
            //    Console.WriteLine(item.Say());
            //}
            //ForEach()结合Lambda表达式实现循环遍历
            students.ForEach(s => { Console.WriteLine(s.Say()); });

            //FindAll方法检索条件匹配的所有元素
           List<Student> _students = students.FindAll(m=>m.Id<3);
            Console.WriteLine("学号小于3的学生如下:");
            _students.ForEach(s => { Console.WriteLine(s.Say()) ; });

            Console.ReadKey();

        }
    }

    public class Student
    {
        public Student(int id,string name)
        {
            this.Id = id;
            this.Name = name;
        }
        //自动属性
        public int Id { get; set; }
        public string Name { get; set; }
        public string Say()
        {
            return "姓名" + Name + ",学号" + Id;
        }

        
    }

Dictionary字典集合创建

 class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(1, "张三");
            dic.Add(2, "李四");
            dic.Add(3, "王五");
            dic[1] = "新来的";
            //foreach(var item in dic.Keys)
            //{
            //    Console.WriteLine("{0}-----{1}", item, dic[item]);
            //}
            foreach (KeyValuePair<int, string> kv in dic)
            {
                Console.WriteLine("{0}--------------{1}", kv.Key, kv.Value);
            }
            Console.ReadKey();
        }
    }

泛型集合常用的扩展方法

 class Program
    {
        static void Main(string[] args)
        {
            Student s1 = new Student(1, "贾宝玉"); 
            Student s2 = new Student(2, "林黛玉");
            Student s3 = new Student(3, "薛宝钗");
            Student s4 = new Student(4, "史湘云");
            //创建泛型集合
            List<Student> students = new List<Student>() { s1, s2, s3, s4 };
            //获取泛型集合中第一个元素,如果泛型内没有元素,则返回null
            //需引入System.Linq命名空间
            var student1 = students.FirstOrDefault();
            Console.WriteLine($"集合中第一个元素的名字是:{student1.Name},其Id是{student1.Id}");
            //判断泛型集合中是不是每个元素的ID都大于0,如果是返回true
            bool b = students.All(s => s.Id > 0);
            Console.WriteLine($"全部学生的ID都大于0:{b}");
            //首先通过where过滤出泛型集合中所有ID大于3的Student,然后再对返回的值求其中的个数
            int count = students.Where(s => s.Id > 3).Count();
            Console.WriteLine($"集合中Id大于3的学生的个数是:{count}");

            Console.ReadKey();

        }
    }

    public class Student
    {
        public Student(int id,string name)
        {
            this.Id = id;
            this.Name = name;
        }
        public int Id { get; set; }
        public string Name { get; set; }
    }

IComparable接口实现排序

//List<string> list = new List<string> { "张三", "李四", "王五" };
            //Console.WriteLine("排序前顺序");
            //foreach (var str in list)
            //{
            //    Console.WriteLine(str);
            //}
            //list.Sort();//按首字符的升序进行排序
            //Console.WriteLine("排序后顺序");
            //foreach (var str in list)
            //{
            //    Console.WriteLine(str);
            //}



            Student stu1 = new Student(1,"张三",19);
            Student stu2 = new Student(2, "李四", 18);
            Student stu3 = new Student(3, "王五", 20);
            List<Student> list = new List<Student>() { stu1,stu2,stu3};
            Console.WriteLine("排序前顺序");
            foreach (Student stu in list)
            {
                Console.WriteLine($"姓名:{stu.name},年龄{stu.age}");
            }
            list.Sort();
            Console.WriteLine("排序后顺序");
            foreach (Student stu in list)
            {
                Console.WriteLine($"姓名:{stu.name},年龄{stu.age}");
            }

            Console.ReadKey();
        }
    }

    //3.实现IComparable接口
    public class Student:IComparable
    {
        public Student(int StuId, string Name, int Age)
        {
            this.stuId = StuId;
            this.name = Name;
            this.age = Age;
        }
        public int stuId;
        public string name;
        public int age;
    //实现IComparable接口的CompareTo()方法
    public int CompareTo(object obj)
        {
            //判断接受的参数是否为Student类的对象
            if(!(obj is Student))
            {
                throw new Exception("比较对象不是Student对象");
            }
            Student other = obj as Student;
            //把当前对象的name成员和接受的参数的name成员进行比较,返回结果
            //返回类型是Int 类型 返回值大于0 表示当前对象大于obj,小于0 ,表示当前对象小于obj,
            return this.name.CompareTo(other.name);
        }

    }

IComparable泛型接口

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

            Student stu1 = new Student(1, "张三", 19);
            Student stu2 = new Student(2, "李四", 18);
            Student stu3 = new Student(3, "王五", 20);
            List<Student> list = new List<Student>() { stu1, stu2, stu3 };
            Console.WriteLine("排序前顺序");
            foreach (Student stu in list)
            {
                Console.WriteLine($"姓名:{stu.name},年龄{stu.age}");
            }
            list.Sort();
            Console.WriteLine("排序后顺序");
            foreach (Student stu in list)
            {
                Console.WriteLine($"姓名:{stu.name},年龄{stu.age}");
            }

            Console.ReadKey();
        }
    }
    //3.实现IComparable<T>泛型接口
    public class Student : IComparable<Student>
    {
        public Student(int StuId, string Name, int Age)
        {
            this.stuId = StuId;
            this.name = Name;
            this.age = Age;
        }
        public int stuId;
        public string name;
        public int age;
        //实现IComparable接口的CompareTo()方法
        public int CompareTo(Student other)
        {
            
            return this.age.CompareTo(other.age);
        }

    }

IComparer泛型接口练习

 class Program
    {
        static void Main(string[] args)
        {
            Student stu1 = new Student(1, "张三", 19);
            Student stu2 = new Student(2, "李四", 18);
            Student stu3 = new Student(3, "王五", 20);
            List<Student> list = new List<Student>() { stu1, stu2, stu3 };
            Console.WriteLine("排序前顺序");
            foreach (Student stu in list)
            {
                Console.WriteLine($"姓名:{stu.name},年龄{stu.age}");
            }
            Console.WriteLine("请选择:1.按姓名排序;2.按年龄排序");
            string select = Console.ReadLine();
            switch (select)
            {
               case "1":
                    //按照姓名排序
                    list.Sort(new NameSort());
                    break;
                case "2":
                    //按年龄排序
                    list.Sort(new AgeSort());
                    break;
            }
            Console.WriteLine("排序后顺序");
            foreach (Student stu in list)
            {
                Console.WriteLine($"姓名:{stu.name},年龄{stu.age}");
            }

            Console.ReadKey();
        }
    }

    public class Student 
    {
        public Student(int StuId, string Name, int Age)
        {
            this.stuId = StuId;
            this.name = Name;
            this.age = Age;
        }
        public int stuId;
        public string name;
        public int age;
    }

   
    //按照姓名首字母升序类
    public class NameSort : IComparer<Student>
    {
        //按照姓名首字符升序排列
        public int Compare(Student x, Student y)
        {
            return x.name.CompareTo(y.name);

        }
    }

    //按照年龄升序类
    public class AgeSort : IComparer<Student>
    {
        //按照姓名首字符升序排列
        public int Compare(Student x, Student y)
        {
            return x.age.CompareTo(y.age);

        }
    }

相关文章

  • Lession11集合和泛型

    创建ArrayList ArrayList的长度 ArrayList的方法 ArrayList存放对象 Array...

  • C#基础提升系列——C#集合

    C#集合 有两种主要的集合类型:泛型集合和非泛型集合。 泛型集合被添加在 .NET Framework 2.0 中...

  • 四、Java高级--1、泛型

    泛型定义:数据类型参数化,提前定义好集合中放入什么类型集合框架中没使用泛型和使用泛型的比较 泛型规则和限制1、泛型...

  • Java—泛型详解和使用

    1 泛型介绍 1.1 泛型的出现   泛型的出现还得从集合说起,没有泛型的时候,我们将一个对象存入集合时,集合不c...

  • JDK5的新特性

    可变参数 格式: 注意 静态导入 泛型 泛型类: 泛型方法: 泛型接口: 增强for 在 集合_List 中有...

  • 泛型——Dart(五)

    泛型 从字面意思理解,就是广泛的类型,我们可以在集合中看到泛型的影子: 为什么要有泛型? 以集合为例,假如没有泛型...

  • 泛型集合与非泛型集合,泛型

    ArrayList//非泛型集合 非泛型集合添加元素演示 public void Test1(){ ArrayLi...

  • 泛型

    泛型的使用 jdk 5.0新增的特性 在集合中使用泛型 ① 集合接口或集合类在jdk5.0时都修改为带泛型的结构。...

  • 《Kotlin入门实战》CH8 | 泛型

    泛型 泛型是在Java5中引入的,泛型让集合框架可以重用代码,在没有泛型时候,集合框架中存储数据的类型都是Obje...

  • 泛型(jdk5.0新特性)

    在集合中使用泛型 1、集合接口或集合类在jdk5.0时都修改为带泛型的结构2、在实例化集合类时,可以指明具体的泛型...

网友评论

      本文标题:Lession11集合和泛型

      本文链接:https://www.haomeiwen.com/subject/wsvmeltx.html