数组声明与初始化

数组

数组的定义:

数组是相同类型数据的有序集合

每一个数据称作一个数组元素,每个数组元素可以通过一个下标引用它们。

数组是相同数据类型(数据类型可以为任意类型)的有序集合

数组也是对象。数组元素相当于对象的成员变量

数组长度是确定的,不可变。如果越界,则报错:ArrayIndexOutofBounds

下标的合法区间:[0,length-1]

数组声明创建

1、首先必须声明数组变量,才能使用数组,声明数组语法:

dataType[] arrayRefVar; //推荐使用

dataType arrayRefVar[];//效果相同,不推荐

2、Java语言使用new操作符创建数组,语法:

dataType[] arrayRefVar = new dataType[arraySize];

3、数组元素通过索引访问,索引从0开始

4、获取数组长度:arrays.length

5、数组初始化:

5.1静态初始化:

int a[] = {1,2,3};

Man mans = {new Man(1,1),new Man(2,2)};

5.2动态初始化:

int a[] = new int[2];

a[0] = 1;

a[1] = 2;

6、数组的默认初始化:

数组是引用类型,它的元素相当于类的实例变量,因此数组一经分配空间,其中的每个元素也被按照实例变量同样的方式被隐式初始化。

public class arrayList {
    public static void main(String[] args) {
        System.out.println(computer(10));
    }

    public static int computer(int n){
        int[] nums = new int[10];
        nums[0] = 1;
        nums[1] = 2;
        nums[2] = 3;
        nums[3] = 4;
        nums[4] = 5;
        nums[5] = 6;
        nums[6] = 7;
        nums[7] = 8;
        nums[8] = 9;
        nums[9] = 10;

        int total = 0;
        for (int i = 0;i < nums.length;i++){
            total = total + nums[i];
        }
        return total;
    }
}
posted @ 2023-09-18 13:18  chengh0618  阅读(43)  评论(0编辑  收藏  举报