实现Java的动态数组

引言

Java是一种面向对象的编程语言,动态数组是一种常用的数据结构,可以根据需要动态调整大小。对于刚入行的小白来说,实现Java的动态数组可能会有一些困惑。本文将带领你一步一步地实现Java的动态数组,并通过表格展示每个步骤和相应的代码,以便你更好地理解和掌握。

整体流程

下面是实现Java的动态数组的整体流程:

步骤 描述
1 创建一个动态数组类
2 定义一个私有数组变量
3 定义一个私有整型变量来保存数组的容量
4 定义一个私有整型变量来保存数组中的元素个数
5 实现构造方法来初始化数组
6 实现添加元素的方法
7 实现获取指定位置元素的方法
8 实现修改指定位置元素的方法
9 实现删除指定位置元素的方法
10 实现获取数组大小的方法
11 实现判断数组是否为空的方法
12 实现打印数组的方法

代码实现

下面是每个步骤所需的代码及其注释:

1. 创建一个动态数组类

public class DynamicArray {
    // 代码实现步骤2~11
}

2. 定义一个私有数组变量

private int[] array;

3. 定义一个私有整型变量来保存数组的容量

private int capacity;

4. 定义一个私有整型变量来保存数组中的元素个数

private int size;

5. 实现构造方法来初始化数组

public DynamicArray(int initialCapacity) {
    if (initialCapacity < 0) {
        throw new IllegalArgumentException("容量不能为负数");
    }
    this.array = new int[initialCapacity];
    this.capacity = initialCapacity;
    this.size = 0;
}

6. 实现添加元素的方法

public void add(int element) {
    if (size == capacity) {
        // 如果数组已满,则扩展数组容量
        int[] newArray = new int[capacity * 2];
        for (int i = 0; i < size; i++) {
            newArray[i] = array[i];
        }
        array = newArray;
        capacity *= 2;
    }
    array[size] = element;
    size++;
}

7. 实现获取指定位置元素的方法

public int get(int index) {
    if (index < 0 || index >= size) {
        throw new IndexOutOfBoundsException("索引越界");
    }
    return array[index];
}

8. 实现修改指定位置元素的方法

public void set(int index, int element) {
    if (index < 0 || index >= size) {
        throw new IndexOutOfBoundsException("索引越界");
    }
    array[index] = element;
}

9. 实现删除指定位置元素的方法

public void remove(int index) {
    if (index < 0 || index >= size) {
        throw new IndexOutOfBoundsException("索引越界");
    }
    for (int i = index; i < size - 1; i++) {
        array[i] = array[i + 1];
    }
    size--;
}

10. 实现获取数组大小的方法

public int size() {
    return size;
}

11. 实现判断数组是否为空的方法

public boolean isEmpty() {
    return size == 0;
}

12. 实现打印数组的方法

public void print() {
    if (isEmpty()) {
        System.out.println("数组为空");
    } else {
        for (int i = 0; i < size; i++) {
            System.out.print(array[i] + " ");
        }
        System.out.println();
    }
}

状态图

下面是动态数组的状态图表示:

stateDiagram
    [*] --> 创建动态数组
    创建动态数组 --> 空数组
    空数组 --> 添加元素
    添加元素 --> 有元素