本文关于第七章数组

数组是什么,数组是相同的东西的组合

数组的申明和初始化

申明,即取名字;初始化,内存中划一片地址给这个变量。

记录几条比较有趣的初始化代码,都是合法的。

int[] a1=new int[4];
int[] a2=new int[4]{1,2,3,4};
int[] a3=new int[]{1,2,3,4};//编译器会自动计数
int[] a4={1,2,3,4};//最大的简化方法

//自定义类型同理
Person[] p={
    new Person("王加乘",13),
    new Person("朗洪刚",14),
}

多维数组

多维数组的申明,需要添加逗号

int[,] a=new int[2,3];//两行三列

int[,] b={
    {1,2,3},
    {4,5,6}
}

int[,,] b={
    { {1,2,3},{4,5,6} },
    { {4,6,9},{2,3,4} }
}

锯齿数组

对于每一行的个数长度不同意的,叫做锯齿数组,类似于

{1,2,3}

{1}

{1,2,3,4,5}

其申明规则如下:

int[][] a=new int[3][];//只需要填写行数就行
a[0]=new int[3]{1,2,3};
a[1]=new int[1]{1};
a[2]=new int[5]{1,2,3,4,5};

遍历规则:

for(int i=0;i<a.Length;i++){
    for(int j=0;j<a[i].Length;j++){
        Console.WriteLine(a[i][j].ToString());
    }
}

区别在于,规则的是int[,],锯齿的是int[][]

Array类

创建数组

这个觉得没什么用,不讲了

复制数组

数组的复制两个方法:Clone和Copy,效果是一样的。

就是Copy方法,需要目标数组有足够的长度。

int[] a = { 1, 5, 2 };
int[] b = (int[])a.Clone();
int[] c = new int[a.Length];
Array.Copy(a, 0, c, 0, a.Length);

a[0] = 11;

Console.WriteLine("a:"+a[0].ToString());
Console.WriteLine("b:"+b[0].ToString());
Console.WriteLine("c:"+c[0].ToString());
===out
a:11 
b:1
c:1
    
A[] a1 = { new A(1, 2), new A(2, 3) };
A[] b1 = (A[])a1.Clone();
A[] c1 = new A[a1.Length];
Array.Copy (a1, 0, c1, 0, a1.Length);

b1[0].y = 0;

Console.WriteLine("a\t" + a1[0].y);
Console.WriteLine("b\t" + b1[0].y);
Console.WriteLine("c\t" + c1[0].y);
===out
a:0 
b:0
c:0

从结果我们可以看出,Clone和Copy的结果是一样的。

对于值类型的数组来说,复制就是真实的拷贝一份数据,是独享的;

对于引用类型的数组来说,复制的只是一个引用地址,是共享的。

使用=会如何?

使用等号,效果就是将新的变量的指针指向a。

等号的右边是是值类型,起赋值作用;

等号的右边是引用类型,起分配引用地址作用。

数组是引用类型,所以等好的作用是分配引用地址。

int[] a = { 1, 5, 2 };
int[] b = (int[])a.Clone();
int[] c = a;//使用等号
Array.Copy(a, 0, c, 0, a.Length);

a[0] = 11;
Console.WriteLine(a[0].ToString());
Console.WriteLine(b[0].ToString());
Console.WriteLine(c[0].ToString());
===out
11
1
11 //和a一同变动

A[] a1 = { new A(1, 2), new A(2, 3) };
A[] b1 = (A[])a1.Clone();
A[] c1 = a1;//使用等号
Array.Copy(a1, 0, c1, 0, a1.Length);
b1[0].y = 0;
Console.WriteLine("a\t" + a1[0].y);
Console.WriteLine("b\t" + b1[0].y);
Console.WriteLine("c\t" + c1[0].y);
==out
a       0
b       0
c       0//和a一同变动

排序

Array.Sort()

使用的前提:实现IComparable接口

public class A : IComparable<A>
{

    public int x { get; set; }
    public int y { get; set; }

    public A(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
    public override string ToString()
    {
        return x.ToString() + "-" + y.ToString();
    }
    public int CompareTo([AllowNull] A other)
    {
        if (other == null) return 1;
        int result = this.x.CompareTo(other.x);
        if (result == 0)
        {
            result = this.y.CompareTo(other.y);
        }
        return result;
    }
}

===Main===
A[] aa = {
    new A(11,2),
    new A(2,13),
    new A(2,3),
    new A(9,2)
};
Array.Sort(aa);
foreach (A a in aa)
{
    Console.WriteLine(a.ToString());
}
===out
2-3
2-13
9-2
11-2