Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java双端队列toString方法覆盖左元素_Java_Collections_Queue_Deque - Fatal编程技术网

Java双端队列toString方法覆盖左元素

Java双端队列toString方法覆盖左元素,java,collections,queue,deque,Java,Collections,Queue,Deque,我已经创建了一个双端队列,我想打印出队列的内容。我创建了一个toString方法,但是当我在左边添加一个元素时,它会覆盖当前的前(左)元素。 比如说 System.out.println(myDeq); myDeq.addFront(7); myDeq.addRight(12); System.out.println(myDeq); myDeq.addFront(15); System.out.println(myDeq); 所以我的输出是 <> <7,12>

我已经创建了一个双端队列,我想打印出队列的内容。我创建了一个toString方法,但是当我在左边添加一个元素时,它会覆盖当前的前(左)元素。 比如说

 System.out.println(myDeq);
 myDeq.addFront(7);
 myDeq.addRight(12);
 System.out.println(myDeq);
 myDeq.addFront(15);
 System.out.println(myDeq);
所以我的输出是

<>
<7,12>
<15,12>

但是我想要

<15,7,12>

我的toString方法是:

public String toString()
    { StringBuffer sb = new StringBuffer("<");
        QCell<T> l = frontCell;
        QCell<T> r = backCell;
        while (l != null && r != null)
        { sb.append(l.data +"," + r.data + ",");
            l = l.next;
            r = r.next;
        }
        return(sb+">");
    }
公共字符串toString()
{StringBuffer sb=新的StringBuffer(“”);
}
我添加到左边的代码是: @凌驾

public void addFront(T x) {
    QCell<T> theCell= new QCell<T>(x);
    if (frontCell == null)
        frontCell = backCell = theCell;
    else {
        frontCell.next = theCell;
        frontCell = theCell;
    }
}
public void addFront(T x){
QCell-theCell=新的QCell(x);
if(frontCell==null)
前电池=后电池=电池;
否则{
frontCell.next=单元格;
前池=前池;
}
}
我不确定是我的toString方法覆盖了它,还是我的addFront代码不正确。

这不应该:

frontCell.next = theCell;
是这个吗

theCell.next = frontCell;

添加Front是错误的,因为将frontCell的下一个设置为Cell。但随后将frontCell重新分配为Cell。原来的前池已经不存在了。首先将其保存在临时单元格中

public void addFront(T x) {
    QCell<T> theCell= new QCell<T>(x);
    QCell<T> tempCell;
    if (frontCell == null)
        frontCell = backCell = theCell;
    else {
        tempCell = frontCell;
        frontCell = theCell;
        frontCell.next = tempCell;
    }
}

为什么不为您的队列编写一个单元测试并找出答案呢?@lancejava这不是我的add方法,我测试了它。这是我的toString方法,但我不明白为什么它会被覆盖。不管是谁写的。编写一个单元测试,调用
add()
toString()
,并做出一些应该为真的断言。继续修复代码,直到测试变绿。没有任何区别。我很确定我的toString方法是不正确的,因为如果我测试removeLeft方法,7仍然存在。是的,它是不必要的复杂,并且不清楚你想要实现什么。你不能从前面到后面浏览一下这个列表吗?
r
变量的作用是什么?
public String toString()
    { StringBuffer sb = new StringBuffer("<");
        QueueCell<T> l = frontCell;
        while (l != null)
        { sb.append(l.data +",");
            l = l.next;
        }

        return(sb+">");
    }