Java数组栈实现字符串转换和增长

我正在尝试使用数组和字符串缓冲区来实现堆栈。让我困惑的是如何正确确定字符串的大小而不聚集字符串中的数组元素。增长应该使我的缓冲区的容量加倍(我尝试使用 Ensurecapacity 来实现)。对于转换,我将数组中的元素附加到缓冲区,但正如已经提到的,现在知道如何在不丢失数组元素的真正含义的情况下执行此操作。


    public class Stack {

    private int[] buffer;

    private int size;


    public Stack(int capacity) {

        //TODO

        buffer = new int [capacity];

        size =0;

    }

    public String toString() {

        StringBuffer converter = new StringBuffer();  //initializing buffer

        int i=0; //

        while(i<=size) { //while loop let's us append the elements of the array into our stringbuffer

            converter.append(buffer[i]+ " ");

        }

            String wanted = converter.toString(); //converting the buffer to a string

            return wanted; 

        } 


    private void grow() {

        //TODO

        StringBuffer doubler = new StringBuffer();

        doubler.append(toString()); //adding our string into the new buffer

        int l = doubler.length();

        doubler.ensureCapacity(l-1); //ensure capacity(if the min argument is smaller than the actual capacity)

    }                                //will take 2*min arg +2 as new capacity

}


浮云间
浏览 63回答 2
2回答

弑天下

不需要使用StringBufferingrow()方法。在grow()方法中,创建一个具有2*buffer.length容量的临时数组,迭代buffer并将元素复制到临时数组,buffer使用临时数组进行更新。

凤凰求蛊

不确定你的grow函数在做什么,但如果你想增加你的函数的大小buffer,你必须创建一个新数组 - 因为数组无法调整大小 - 并将旧数据复制到新数组。然后将缓冲区重新分配给新数组:private void grow() {&nbsp; &nbsp; int [] temp = new int[buffer.length * 2];&nbsp; &nbsp; for (int i = 0; i < size; i++) {&nbsp; &nbsp; &nbsp; &nbsp; temp[i] = buffer[i];&nbsp; &nbsp; }&nbsp; &nbsp; buffer = temp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java