如何在不使用内置方法的情况下将项目添加到数组

AAA*_*AAA 1 java arrays data-structures

我创建一个数组类,我想实现方法addremove以及replace

但我不想使用任何内置的内部结构。

public class MySet {

    public int set[];
    private int size = 0;

    public MySet(int size) {
        this.set = new int[size];
    }

    public boolean add(int item) {
        for (int i = 0; i < this.size(); i++) {
            if (this.set[i] != 0) {
                // add to array
            }
        }
        this.size++;
        return true;
    }

    public int size()
    {
        return this.size;
    }
}
Run Code Online (Sandbox Code Playgroud)

当你在 Java 中初始化一个固定大小的数组时,每一项都等于0。部分if this.set[i] != 0是我被困在添加项目的地方。

我应该使用带有指针的 while 循环吗?如:

public boolean add(int item) {
    int index = 0;
    while (index <= this.size()) {
        if (this.set[index] != 0 || index <= ) {
            // increase pointer
            index++;
    }
    this.set[index] = item;
}
Run Code Online (Sandbox Code Playgroud)

但是如果我在列表中有一个数组,例如 [7, 2, 0 , 1] ,它不会得到我需要的循环中的最后一项。

那么,这通常是如何完成的呢?

Ami*_*n J 5

您应该保留size看起来像您一样的填充元素的当前索引。当您添加set[size]= item并增加大小时。一旦size达到数组的预分配大小,您需要创建一个大小增加的新数组(例如可以选择两倍大小)并将旧数组复制到新数组。