Detailed Explanation of ArrayList Class in C#

Table of contents

1. ArrayList class definition

Second, the difference between the ArrayList class and the array

3. Declaration of ArrayList class object

1. The default constructor

2. Use an ICollection object to construct

3. Initialize the internal array with the specified size

4. Common properties of ArrayList

5. Common methods of ArrayList

1. Adding ArrayList elements 

(1) Add() method

(2) Insert () method

(3) Comprehensive example

2. Deletion of ArrayList elements

(1) Clear() method

(2) Remove() method

(3) RemoveAt() method

(4) RemoveRange () method

(5) Comprehensive example

3. Search for ArrayList elements

(1) Contains () method

(2) IndexOf () method

(3) LastIndexOf() method

4. Traversal of ArrayList

1. ArrayList class definition

          The ArrayList class is equivalent to an advanced dynamic array , which is an upgraded version of the Array class.

        The ArrayList class is located in the System.Collections namespace, and it can dynamically add and remove elements. You can think of the ArrayList class as an array with extended functionality, but it is not equivalent to an array. Use the ArrayList class to add references:

        using System.Collections;

Second, the difference between the ArrayList class and the array

        Compared to Array, ArrayList class provides the following features to the developer.

        ☑ The capacity of the array is fixed, while the capacity of the ArrayList can be automatically expanded as needed.

        ☑ ArrayList provides methods for adding, deleting and inserting a range of elements, but in an array, only one element value can be obtained or set at a time.

        ☑ ArrayList provides read-only and fixed-size packaging methods to return collections, while arrays do not.

        ☑ ArrayList can only be one-dimensional, while arrays can be multi-dimensional.

        The length of an Array is the total number of elements it can contain. The rank of an Array is the number of dimensions in the Array. The lower limit of a dimension in the Array is the starting index of the dimension in the Array, and each dimension of a multidimensional Array can have different limits.

3. Declaration of ArrayList class object

        ArrayList provides 3 constructors, through which there are 3 declaration methods:

1. The default constructor

        Initializes the internal array with the default (16-bit) size.

        Constructor format: public ArrayList();

        The syntax format of ArrayList is declared through the above constructor:

        ArrayList List=new(); // List : ArrayList object name.

ArrayList List=new();	 //List:ArrayList对象名
for(i=0;i<10;i++)        //给ArrayList类对象添加10个int型元素
{
    List.Add(i);
}

2. Use an ICollection object to construct

        And add the elements of the collection to the ArrayList.

        Constructor format: public ArrayList(ICollection);

        The syntax format of ArrayList is declared through the above constructor:

        ArrayList List=new( arrayName);

        ☑ List: ArrayList object name.

        ☑ arryName: the name of the array to add the collection.

int[]arr=new int[]{1,2,3,4,5,6,7,8,9};
ArrayList List=new(arr);

3. Initialize the internal array with the specified size

        Constructor format: public ArrayList(int);

        The syntax format of ArrayList is declared through the above constructor:

        ArrayList List=new(n);

        ☑ List: ArrayList object name.

        ☑ n: the space size of the ArrayList object.

ArrayList List=new(10);
for(int i=0;i<List.Count;i++)
{
    List.Add(i);    //给ArrayList添加10个int型元素
}

4. Common properties of ArrayList

Attributes

illustrate

Capacity

Get or set the number of elements that the ArrayList can contain

Count

Get the number of elements actually contained in the ArrayList

IsFixedSize

Gets a value indicating whether the ArrayList has a fixed size

IsReadOnly

Gets a value indicating whether the ArrayList is read-only

IsSyncronized

Gets a value indicating whether to synchronize access to the ArrayList

Item

Gets or sets the element at the specified index

SyncRoot

Get an object that can be used to synchronize ArrayList access

5. Common methods of ArrayList

1. Adding ArrayList elements 

(1) Add() method

        The Add() method is used to add objects to the end of the ArrayList collection, and its syntax format is:

        public virtual int Add(Object value);

        ☑ value: Object to be added to the end of the ArrayList, the value can be a null reference.

        ☑ Return value: ArrayList index, value has been added here.

        ArrayList allows null values ​​as valid values ​​and allows duplicate elements.

int arr[] =new int[]{1,2,3,4,5,6};
ArrayList List = new (arr);	//使用声明的数组实例化ArrayList对象
List.Add(7);			    //为ArrayList对象添加元素

(2) Insert () method

        The Insert() method is used to insert elements into the specified index of the ArrayList collection, and its syntax format is:

        public virtual void Insert(int index, Object value)

        ☑ index: The zero-based index at which value should be inserted.

        ☑ value: Object to be inserted, the value can be a null reference.

        If the actual number of elements stored in the ArrayList is already equal to the number of elements that the ArrayList can store, the capacity of the ArrayList will be increased by automatically reallocating the internal array, and the existing elements will be copied to the new array before adding new elements. 

int[] arr = new int[]{1,2,3,4,5,6};
ArrayList List = new(arr);	//使用声明的数组实例化ArrayList对象
List.Insert(3,7);			//在ArrayList对象索引值=3处添加元素7

(3) Comprehensive example

//Add()方法和Insert()方法
//分别使用ArrayList对象的Add()方法和Insert()方法向ArrayList集合的结尾处和指定索引处添加元素
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Test7_12
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args is null)                           //解除IDE0060
            {
                throw new ArgumentNullException(nameof(args));
            }
            int[] arr = new int[] { 1, 2, 3, 4, 5, 6 };
            ArrayList List = new(arr);                  //使用声明的一维数组实例化一个ArrayList对象
            Console.WriteLine("原ArrayList集合:");
            foreach (int i in List)					    //遍历ArrayList源集合并输出
            {
                Console.Write(i + " ");
            }
            Console.WriteLine();

            for (int i = 1; i < 5; i++)
            {
                List.Add(i + arr.Length);			    //使用Add()方法为ArrayList集合添加元素
            }
            Console.WriteLine("使用Add方法添加:");
            foreach (int i in List)					    //遍历添加元素后的ArrayList集合并输出
            {
                Console.Write(i + " ");
            }
            Console.WriteLine();

            List.Insert(6,0);						    //使用Insert()方法在ArrayList集合的index=6处添加元素0
            Console.WriteLine("使用Insert方法添加:");
            foreach (int i in List)					    //遍历最后的ArrayList集合并输出
            {
                Console.Write(i + " ");
            }
            Console.WriteLine();
            Console.Read();
        }
    }
}
/*运行结果:
原ArrayList集合:
1 2 3 4 5 6
使用Add方法添加:
1 2 3 4 5 6 7 8 9 10
使用Insert方法添加:
1 2 3 4 5 6 0 7 8 9 10  */

2. Deletion of ArrayList elements

(1) Clear() method

        The Clear() method is used to remove all elements from the ArrayList, its syntax format is:

        public virtual void Clear()

//使用 Clear()方法清除ArrayList中的所有元素
int[] arr = new int[]{1,2,3,4,5,6};
ArrayList List = new (arr);	//使用声明的数组实例化ArrayList对象
List.Clear();			    //在ArrayList对象指定位置添加元素

(2) Remove() method

        The Remove() method is used to remove the first occurrence of a specific object from the ArrayList, its syntax format is:

        public virtual void Remove(Object obj)

        obj: The Object to be removed from the ArrayList, this value can be a null reference.

        When deleting elements in the ArrayList, if the specified object is not contained, the ArrayList will remain unchanged.

//使用RemoveAt()方法从声明的ArrayList对象中移除与3匹配的元素
int[] arr = new int[]{1,2,3,4,5,6};
ArrayList List = new(arr);	//使用声明的数组实例化ArrayList对象
List.Remove(3);			    //删除ArrayList对象指定位置元素

(3) RemoveAt() method

        The RemoveAt() method is used to remove the element at the specified index of the ArrayList, and its syntax format is:

        public virtual void RemoveAt(int index)

        index: The zero-based index of the element to remove.        

//使用RemoveAt()方法从声明的ArrayList对象中移除索引为3的元素
int[] arr = new int[]{1,2,3,4,5,6};
ArrayList List = newt(arr);	//使用声明的数组实例化ArrayList对象
List.RemoveAt(3);		    //删除ArrayList对象指定位置元素

(4) RemoveRange () method

        The RemoveRange() method is used to remove a certain range of elements from the ArrayList, and its syntax format is:

        public virtual void RemoveRange(int index,int count)

        ☑ index: The zero-based starting index of the range of elements to remove.

        ☑ count: the number of elements to remove.

        In the RemoveRange() method, the length of the parameter count cannot exceed the total length of the array minus the value of the parameter index.

//在ArrayList对象中使用RemoveRange()方法从索引3处删除两个元素
int[] arr = new int[]{1,2,3,4,5,6};
ArrayList List = new (arr);	   //使用声明的数组实例化ArrayList对象
List.RemoveRange(3,2);	       //删除ArrayList对象指定位置3处2个元素

(5) Comprehensive example

//RemoveRange()
//使用RemoveRange()方法删除ArrayList集合中的一批元素
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Test7_13
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args is null)           //解除IDE0060
            {
                throw new ArgumentNullException(nameof(args));
            }
            int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            ArrayList List = new(arr);  //使用声明的一维数组实例化一个ArrayList对象
            Console.WriteLine("原ArrayList集合:");
            foreach (int i in List)     //遍历ArrayList集合中的元素并输出
            {
                /*Console.Write(i+ " ");*/  //可以注释掉.ToString()不影响结果
                Console.Write(i.ToString() + " ");
            }

            Console.WriteLine();
            List.RemoveRange(0, 5);     //从索引0处开始删除5个元素
            Console.WriteLine("删除元素后的ArrayList集合:");
            foreach (int i in List)     //遍历删除元素后的ArrayList集合并输出其元素
            {
                Console.Write(i.ToString() + " ");
            }
            Console.WriteLine();
            Console.Read();
        }
    }
}
/*运行结果:
原ArrayList集合:
1 2 3 4 5 6 7 8 9
删除元素后的ArrayList集合:
6 7 8 9     */

3. Search for ArrayList elements

(1) Contains () method

        The Contains() method is used to determine whether an element is in the ArrayList collection, and its syntax format is:

        public virtual bool Contains(Object item)

        ☑ item: the Object to be searched in the ArrayList, this value can be a null reference.

        ☑ Return value: true if the item is found in the ArrayList; otherwise, false.

//使用 Contains()方法判断数字2是否在ArrayList集合中
int[] arr = new int[]{1,2,3,4,5,6};
ArrayList List = new (arr);	   	    //使用声明的数组实例化ArrayList对象
Console.Write(List.Contains(2));	//ArrayList集合中是否包含指定的元素

(2) IndexOf () method

Used to find the first occurrence of         a character or string .

        The IndexOf() method is represented by the following syntax:

public int IndexOf(String value);                  //语法1
public int IndexOf(char value);                    //语法2
public int IndexOf(String value, int startIndex);  //语法3
public int IndexOf(char value, int startIndex);    //语法4

☑ value: Specify the character or string to be searched.

☑startIndex: Specify the position to start searching.

Returns the position of the first occurrence of a character or string, indexed from 0.

//IndexOf()
//查找字符或者字符首次出现的位置
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace yxjc123
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args is null)                                           //解除IDE0060
            {
                throw new ArgumentNullException(nameof(args));
            }
            string str = "yxjc123.com  repeat yxjc123.com";            //原字符串

            Console.WriteLine("查找j:" + str.IndexOf('j'));           //查找字符j
            Console.WriteLine("查找123:" + str.IndexOf("123"));       //查找字符串123

            Console.WriteLine("查找j:" + str.IndexOf('j', 10));       //查找字符j,从开始位置10开始
            Console.WriteLine("查找123:" + str.IndexOf("123", 10));   //查找字符串123,从开始位置10开始

            Console.ReadKey();
        }
    }
}
/*运行结果:
查找j:2
查找123:4
查找j:22
查找123:24    */

(3) LastIndexOf() method

        Used to find the last occurrence of a character or string.

        The LastIndexOf() method is represented by the following syntax:

public int LastIndexOf(String value);                   //语法1
public int LastIndexOf(char value);                     //语法2
public int LastIndexOf(String value, int startIndex);   //语法3
public int LastIndexOf(char value, int startIndex);     //语法4

        ☑ value: Specify the character or string to be searched.

        ☑ startIndex: Specify the starting position to search, counting from the end .

        Returns the position of the last occurrence of a character or string.

//LastIndexOf()
//用于查找字符或者字符串最后出现的位置

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace yxjc123
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args is null)                                               //解除IDE0060
            {
                throw new ArgumentNullException(nameof(args));
            }
            string str = "yxjc123.com  repeat yxjc123.com";                 //原字符串

            Console.WriteLine("查找j:" + str.LastIndexOf('j'));           //查找字符j
            Console.WriteLine("查找123:" + str.LastIndexOf("123"));       //查找字符串123

            Console.WriteLine("查找j:" + str.LastIndexOf('j', 10));       //查找字符j,倒数从开始位置10开始
            Console.WriteLine("查找123:" + str.LastIndexOf("123", 10));   //查找字符串123,倒数从开始位置10开始
            Console.ReadKey();
        }
    }
}
/*运行结果:
查找j:22
查找123:24
查找j:2
查找123:4   */

4. Traversal of ArrayList

        The traversal of the ArrayList collection is similar to the array, and the foreach statement can be used. The following example illustrates how to traverse the elements in the ArrayList collection.

//ArrayList的遍历
//使用foreach语句遍历ArrayList集合中的各个元素并输出

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Test7_14
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args is null)               //解除IDE0060
            {
                throw new ArgumentNullException(nameof(args));
            }
            ArrayList list = new()          //实例化一个ArrayList对象并赋值
            {
                "TM",
                "C#从入门到精通"
            };                              
            foreach (string str in list)    //遍历ArrayList集合中的元素并输出
            {
                Console.WriteLine(str);
            }
            Console.ReadLine();
        }
    }
}
/*运行结果:
TM
C#从入门到精通    */

Guess you like

Origin blog.csdn.net/wenchm/article/details/131480220