简体   繁体   English

如何调整 Java 中的数组大小?

[英]How to resize the array in Java?

I have been trying to create my own Array class, which is dynamic, but I can't figure out the problem in resizing the size of it.我一直在尝试创建自己的Array class,它是动态的,但我无法弄清楚调整其大小的问题。 I created separate function to check if the array is full and for resizing it.我创建了单独的 function 来检查数组是否已满并调整它的大小。 But I think it is unable to call either one of those.但我认为它无法调用其中任何一个。

public class Array {
    private int[] array;
    private int size;
    public int pointer;
    private static int DEFAULT_SIZE = 5;
    
    Array() {
        this(DEFAULT_SIZE);
    }
    
    Array(int size) {
        this.size = size;
        this.array = new int[size];
    }
    
    public void add(int element) {
        if (isFull()) {
            resize();
        }
        array[pointer] = element;
        pointer++;
    }

    private boolean isFull() {
        return pointer == array.length;
    }

    private void resize() {
        int[] temp = new int[size * 2];
        for (int i = 0; i < array.length; i++) {    
            temp[i] = array[i];
        }
        array = temp;
    }
    
    public void print() {
        for (int i = 0; i < size; i++) {
            System.out.println(array[i]);
        }
    }
}

You are never updating the size after allocating the bigger array:分配更大的数组后,您永远不会更新size

private void resize() {
    int[] temp = new int[size * 2];
    for (int i = 0; i < array.length; i++) {    
        temp[i] = array[i];
    }
    array = temp;   
}

This will leave size at the initial value of 5 .这将使size保持初始值5 You have to add size *= 2 at the end of your method (or at the start and then only do new int[size] ).您必须在方法的末尾添加size *= 2 (或在开始时然后只执行new int[size] )。

Please note that the size field is totally redundant, because it is already tracked and accessible via array.length (which you are already using in your loop's condition).请注意, size字段是完全多余的,因为它已经通过array.length (您已经在循环条件中使用)进行跟踪和访问。

print seems to be incorrect, as it always prints the full array, even the items which have not been added yet. print似乎是不正确的,因为它总是打印完整的数组,甚至是尚未添加的项目。 You likely want to user pointer instead of size (otherwise, you are going to print lots of zeros):您可能希望使用pointer而不是size (否则,您将打印很多零):

public void print() {
    for (int i = 0; i < pointer; i++) {
        System.out.println(array[i]);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM