1.数组
//数组存储的是一组相同类型的值
//数组定义必须要给定长度
//类型确定 长度也确定
//类型 [] 数组名 = new 类型[长度];
//1
/*int [] nums = new int[5] ;
//2
int [] counts = new int[3] {1,2,3};
//3
int [] Scores = new int[] {1,2,3,5,8};
//4
int [] Prices = {10,15,3,6,8,9};
2.集合
//泛型集合
//类型确定,长度不定
List <int> nums = new List<int> ();
//列表添加元素
nums.Add (1);
nums.Add (2);
nums.Add (3);
//删除元素
//nums.Remove (2);
Console.WriteLine (nums [1]);
//删除相应索引位置上的元素
//nums .RemoveAt (1);
Console.WriteLine (nums .Count);
Console.WriteLine (nums [0]);
for (int i = 0;i<nums .Count ;i++){
Console.WriteLine (nums [i]);
}
//list <类型> 列表名 = new List <类型>();
List <string> names = new List<string> ();
for (int i = 0;i<11;i++){
nums.Add (i);
}
//列表取值使用索引
//集合ArrayList
//类型不固定,长度不固定
ArrayList array = new ArrayList ();
array.Add (2);
array.Add ("4");
//int num = (int)array [1];
//array.Remove (2);
//array.RemoveAt (0);
Console.WriteLine (array [0]);
Object n = 2;//装箱
int n1 = (int)n;//拆箱
//ArrayList 在存储和取值的过程中会发生装箱和拆箱的操作
//装箱和拆箱 可能会存在不安全类型
for (int i = 0;i <array .Count ;i++){
Console.WriteLine (array [i]);
}
foreach (Object obj in array ){
Console.WriteLine (obj);
}
//字典 Dictionary
//字典的存储是无序的
//key键 value值
Dictionary <string ,string > Users =new Dictionary<string, string>();
Users.Add ("111","555");
Users.Add ("222","666");
Users.Add ("333","777");
//删除键就会删除对应的值
Users.Remove ("111");
//字典取值是通过key 来取值的
Console.WriteLine (Users ["222"]);
foreach(string str in Users .Keys){
Console.WriteLine (str);
}
//for 和foreach
//遍历速度几乎没有差别
//foreach 会在内存上产生垃圾
//for 循环可以一边遍历一边修改
//foreach 是只读的,不能一边遍历一边修改。
foreach (string str in Users .Values ){
Console.WriteLine (str);
}
本文深入讲解了数组与集合的基本概念及用法,包括数组的定义与初始化方式、泛型集合的特点与操作方法、ArrayList的类型灵活性及Dictionary的键值对存储方式等。此外还对比了for循环与foreach循环在遍历集合时的区别。
2478

被折叠的 条评论
为什么被折叠?



