JavaSE - 数组

1. 数组基本概念

  • 定义:数组是多个相同类型数据的组合,用于统一管理数据。

  • 元素:数组中的每个数据称为数组的元素。

  • 数据类型:数组元素可以是基本数据类型或引用类型。

  • 长度(length):数组中元素的个数,声明时不能指定长度。

  • 示例

    int[] a = new int[5]; // 正确
    int a[5]; // 错误

2. 一维数组操作

2.1 一维数组的声明

int[] array; // 声明一个整型数组

2.2 一维数组的创建

array = new int[5]; // 创建一个长度为5的数组

2.3 数组的内存模型

  • 数组是对象,存储在堆内存中。

  • 数组创建后立即拥有默认值(如int默认为0)。

  • 索引从0开始,连续分配。

2.4 数组的初始化

int[] array = new int[]{1, 2, 3, 4, 5}; // 初始化数组

2.5 数组元素访问

int value = array[0]; // 访问数组的第一个元素

2.6 数组的长度

  • length是数组的只读属性,表示数组的长度。

  • 示例:int length = array.length;

2.7 数组遍历

  • 普通for循环

    for (int i = 0; i < array.length; i++) {
        System.out.println(array[i]);
    }
  • 增强for循环

    for (int value : array) {
        System.out.println(value);
    }

2.8 数组的异常

  • 常见异常:ArrayIndexOutOfBoundsException(数组索引越界)。

3. 多维数组

3.1 多维数组概念

  • 多维数组是数组的数组,如二维数组。

3.2 二维数组声明

int[][] matrix;

3.3 二维数组创建

matrix = new int[3][4]; // 创建一个3行4列的二维数组

3.4 二维数组初始化

int[][] matrix = {
    {1, 2},
    {3, 4, 5, 6},
    {7, 8}
};

3.5 二维数组内存表示

  • 二维数组的每个元素本身是一个数组。

3.6 二维数组遍历

  • 普通for循环

    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[i].length; j++) {
            System.out.println(matrix[i][j]);
        }
    }
  • 增强for循环

    for (int[] row : matrix) {
        for (int value : row) {
            System.out.println(value);
        }
    }

4. 数组的复制

  • 使用System.arraycopy()方法复制数组。

    int[] source = {1, 2, 3, 4, 5};
    int[] target = {6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
    System.arraycopy(source, 0, target, 0, source.length);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值