文章目录
ArrayList元素增加
集合添加数据
在数组中放各种类型的数据,并且不确定数量。
ArrayList al= new ArrayList();
al.Add(23);//Add()方法在集合中可以添加任何类型的数据
al.Add("哈哈");
arrayList[0] = 10;//利用索引可以对数据重新赋值,但不能添加新的数据
arrayList[1] = "呵呵";
集合添加数组
在集合中添加数组,并显示数组中数据
case1:Add方法
ArrayList arrayList = new ArrayList();
arrayList.Add(23);
arrayList.Add("哈哈");
arrayList.Add(true);
arrayList.Add(43.5);
int[] nums = new int[] { 1, 2, 3, 4, 5 };
arrayList.Add(nums);
for (int i = 0; i < arrayList.Count ; i++)//遍历集合中的数据
{
if(arrayList[i] is int [])//判断数据是否是int数组
{
int []numbers = (int[])arrayList[i];//将遍历出的数组放到数组numbers中
for (int j = 0; j < numbers.Length ; j++)
{
Console.WriteLine(numbers[j]);//遍历显示数组中的数据
}
}
else
{
Console.WriteLine(arrayList[i]);
}
}
Console.ReadKey();
case2:AddRange方法:继承接口
ArrayList arrayList = new ArrayList();
int[] nums = new int[] { 1, 2, 3, 4, 5 };
arrayList.AddRange(nums);//显示数组中数据
case3:重载方法,ArrayList(ICollection c)
int[] nums = new int[] { 1, 2, 3, 4, 5 };
ArrayList arrayList = new ArrayList(nums);//显示数组中数据
集合添加类
ArrayList arrayList = new ArrayList();
person p = new person("小帅", '男', 34);
arrayList.Add(p);
if(arrayList[i] is person)//判断数据是否是person类
{
((person)arrayList[i]).SayHi();//调用person类中的方法
}
else
{
Console.WriteLine(arrayList[i]);
}
}
Console.ReadKey();
ArrayList元素
insert(插入)
集合中已有数据:1,3,5,7,9,向其中插入2,4,6,8,10.
ArrayList al = new ArrayList();
al.Add(1);
al.Add(3);
al.Add(5);
al.Add(7);
al.Add(9);
for (int i = 1; i <=10; i+=2)
{
al.Insert(i, i+1);//(插入的索引位置,插入的数据)
}
for (int i = 0; i < al.Count ; i++)
{
Console.WriteLine(al[i]);
}
Console.ReadKey();
clear(清空)
al.Clear();
Contains(判断元素是否在集合中)
bool result=al.Contains(2)
Console.WriteLine(result);
IndexOf(找某个元素对应的索引)
int num=al.IndexOf(4);
Count(集合中的元素数)
int num=al.Count;
InsertRange(根据索引位置添加数据)
int[] num = { 1, 2, 3 };
al.InsertRange(1, num);//在索引为1的位置添加num数组的数据
Console.WriteLine();
Remove(移除集合中数据)
al.Remove(3);//移除集合中的3
RemoveAt(移除索引对应的值)
al.RemoveAt(0);//移除索引为0对应的值
RemoveRange(从指定索引处移除一定数量的数据)
al.RemoveRange(0, 2);//移除从索引0开始的2个值
Reverse(反转数据)
al.Reverse();//将集合中数据反转
al.Reverse(0, 5);//从索引0开始,反转5个数据
Sort(数据排序)
al.Sort();//将集合中的数据进行排序
集合练习
随机往集合中添加数据,添加10个,不能重复。求和、平均值
ArrayList al = new ArrayList();
double sum = 0;
Random r = new Random();
while (al.Count!=10)
{
int num = r.Next(1, 101);
if (!al.Contains(num))//不能重复
{
al.Add(num);
}
}
for (int i = 0; i < al.Count; i++)
{
if(al[i] is int)
{
sum += (int)al[i];
}
}
Console.WriteLine(sum);
Console.WriteLine(sum/al.Count );
Console.ReadKey();