简体   繁体   English

用相同的名称在Java中调整数组大小

[英]Resize an Array in Java with same name

I'm trying to resize an array to my 'push' method, but in the output the number '6' it's not there. 我正在尝试将数组的大小调整为我的“推”方法,但是在输出中没有数字“ 6”。

Any clue? 有什么线索吗?

public void push(int value) {
        if (size != maxSize){ 
            top++;
            stackArray[top] = value;
            size++;
        }else if (size == maxSize){
            stackArray = Arrays.copyOf(stackArray, size * 2);
            maxSize = size * 2;
            size++;
        }else{
            throw new RuntimeException();
        }
    }

Pop method 弹出方法

public int pop() {
        if (size != 0){
            size--;
            return stackArray[top--];
        } else {
            throw new RuntimeException();
        }
    }

I put some elements on that stack 我在堆栈上放了一些元素

Stack theStack= new Stack(5);

    theStack.push(1);
    theStack.push(2);
    theStack.push(3);
    theStack.push(4);
    theStack.push(5);
    theStack.push(6);
    theStack.push(7);

    System.out.println(theStack.pop());
    System.out.println(theStack.pop());
    System.out.println(theStack.pop());
    System.out.println(theStack.pop());
    System.out.println(theStack.pop());
    System.out.println(theStack.pop());

And then i've got this 然后我有这个

7 5 4 3 2 1 7 5 4 3 2 1

In the case size == maxSize , you don't add 6 after resizing the array. size == maxSize的情况下,调整数组大小后不添加6。 Please modify your method to something like this. 请将您的方法修改为这样。

Now, you are resizing first (if required). 现在,您首先要调整大小(如果需要)。 Then do your insertion as normal. 然后照常插入。

public void push(int value) {
    // resize if required
    if (size == maxSize){
        stackArray = Arrays.copyOf(stackArray, size * 2);
        maxSize = size * 2;
    }

    // then do the addition to the array stuff
    if (size != maxSize){ 
        top++;
        stackArray[top] = value;
        size++;
    } else {
        throw new RuntimeException();
    }
}

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

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