有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

为泛型队列类生成toString()方法时出现java逻辑错误

我试图为使用ArrayList的通用队列创建一个toString()方法。我在for循环中遇到了一些问题,它使用StringBuilder来生成toString()方法返回的字符串

当我尝试使用toString()打印其中一个对象时,我得到Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1。 我认为问题在于在线阅读T element = q.get(front - k);,但我不是很确定

(变量front引用队列的前面,它是下一个要退出队列的数字)

public String toString() {

    //Create new StringBuilder
    StringBuilder sBuilder = new StringBuilder();

    //If q is empty, return so
    if(isEmpty())
        sBuilder.append("The queue is currently empty" + "\n");

    //else make the string
    else {

        sBuilder.append("The next item to get removed is " + front + ";\n");

        //for loop to create the rest of the list
        for (int k = 0; k < getSize(); k++) {

            //Set the element num, and find the element.
            int elementNum = k + 1;
            T element = q.get(front - k);

            //Print that element
            sBuilder.append("Element " + elementNum + " is " + element + ";\n");
        }
    }

    //return StringBuilder
    return sBuilder.toString();
}

这是排队的方法

public void enqueue(T t) {

    //Add to queue
    size++;
    q.add(rear, t);
    rear++;

}

这是出列的方法

public T dequeue() {

    //Minus Size
    size--;

    //Set the value to value
    T value = q.get(front);

    //set front equal to null for garbage collection
    q.set(front, null);

    //Update front
    front++;

    //return value
    return value;

}

我还有int getSize()方法和isEmpty()方法


共 (1) 个答案

  1. # 1 楼答案

    好吧,我真的需要看到完整的实现才能确定,但我认为这就是它的工作原理。你的前面和后面都可能从零开始,当你添加元素时,你会增加后面,所以队列中后面的元素有更高的索引

    假设我们从一个空队列开始,添加3个元素。前部为0,后部为3,尺寸为3。(注:尺寸不需要变量,只需使用后减前)。所以当你做q.get(front-k)时,你会试图得到索引0处的元素(到目前为止还行),-1和-2(这就是你得到错误的地方)。您需要执行q.get(前+k)或q.get(后-k),这取决于您希望打印元素的顺序