您的位置:首页 > 理论基础 > 数据结构算法

数据结构与算法C#语言描述第二章数组与ArrayList类

2010-05-16 18:57 267 查看
第二章 数组与ArrayList
数组时最通用的数据结构,它几乎出现在所有的编程语言里。
Array类提供了一套方法,这些方法是为了执行诸如排序和查找这类过去需要程序员手工实现的任务。ArrayList是一种需要更多空间来动态生长的数组。
本章简要介绍C#语言中使用数组的基本概念,然后继续展开更加深入的主题,其中包括复制、克隆、相等判定,以及使用array类和arrayList类的静态方法。
2.1数组基本概念
2.1.2数组元素的设置和存取访问
Names[2]=”Raymond”;
Sales[19]=23123;
Names.SetValue(“Raymond”,2);
Sales.SetValue(23123,19);
myName=names[2];
monthSales=sales.GetValue(19);
for(int i=0;i<=sales.GetUpperBound(0);i++)
totalSales=totalSales+sales[i];
2.1.2检索数组元数据的方法和属性
属性:Length,GetLength, Rank, GetType
int[] numbers;
numbers = new int[] { 0, 1, 2, 3, 4 };
Type arrayType = numbers.GetType();
if (arrayType.IsArray)
Console.WriteLine("the array type is:{0}", arrayType);
else
Console.WriteLine("is not an array");
2.1.4多维数组
在C#语言中,数组可以多达32维的。
二维数组的声明:
int[ ,] grades=new int[4,5];
int[ ,] grades=new int[ ,]
{
{1,82,74,89,100},
{2,93,96,85,86},
{3,83,72,95,89}
{4,91,98,79,88}
};
2.1.5参数数组
2.1.6锯齿状数组锯齿状数组是一种每行都能组成一个数组的数组。锯齿状数组的每一维就是一个一维数组,大家称其为“锯齿状”数组的原因是由于数组每一行元素的数量都可能不相同
int [][] jagged=new int[12][];
jagged是一个有着12个元素的整数数组,其中的每个元素又是一个整数数组。
复制操作
Jagged[0][0]=23;
……………
class chapter1
{
static void Main()
{
int[] Jan = new int[31];
int[] Feb = new int[29];
int[][] sales = new int[][] {Jan,Feb };
int month, day, total;
double average = 0.0;
sales[0][0] = 41;
sales[0][1] =30;
sales[0][2] = 23;
sales[0][3] = 34;
sales[0][4] = 28;
sales[0][5] = 35;
sales[0][6] = 45;
sales[1][0] = 35;
sales[1][1] = 37;
sales[1][2] = 32;
sales[1][3] = 35;
sales[1][4] = 35;
sales[1][5] = 35;
sales[1][6] = 35;
for (month = 0; month <= 1; month++)
{
total = 0;
for (day = 0; day <= 6; day++)
{
total += sales[month][day];
}
average = total / 7;
Console.WriteLine("Average sales for month:" + month + ":" + average);
}
}
2.2ArrayList类
当无法提前知道数组的大小或者在程序运行期间数组的大小可能会发生改变的时候,静态数组就不是很适用了。
ArrayList对象拥有可存储数组大小尺寸的capacity属性,该属性的初始值是16
ArrayList用object类型来存储对象。如果需要强类型的数组,就应该采用标准数组或者其他一些数据结构。
2.2.1ArrayList类的成员:方法和属性
2.2.2应用ArrayList类
ArrayList grades = new ArrayList();
grades.Add(100);
grades.Add(84);
int position;
position = grades.Add(77);
Console.WriteLine("The grade 77 was added at position:" + position);
int total=0;
double average;
foreach (Object grade in grades)
total += (int)grade;
average = total / grades.Count;
Console.WriteLine("The average grade is:" + average);
Console.WriteLine(grades.Capacity);
Console.WriteLine(grades.Count);
AddRange添加到末尾 InsertRange添加到指定位置
ToArray允许把ArrayList的内容传递给一个标准数组。
GetRange(2,4)从某一个数组中第二个开始取出4个
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: