Java Queue Peek()始终返回最新条目,而不是首先输入

时间:2018-11-13 22:49:19

标签: java queue

我试图窥视我的队列并获取第一个条目,因此我可以按删除按钮将其删除,但是窥视显示的是最后输入的而不是第一个。我已经尝试过窥视和窥视前端。

private int maxSize;
private String[] queArray;
private int front;
private int rear;
private int nItems;
public String FN,LN,PN,Email,Addres,State,Zip,LicensePlate;

public Queue(String fN, String lN, String pN, String email, String address, String state, String zip,
        String licensePlate) {

    maxSize++;

    queArray = new String[maxSize];
    front = 0;
    rear = -1;
    nItems = 0;
    FN = fN;
    LN = lN;
    PN = pN;
    Email = email;
    Addres = address;
    State = state;
    Zip = zip;
    LicensePlate = licensePlate;

}

public void insert(String FN, String LN, String PN, String Email, String Addres, String State, String Zip,
        String LicensePlate) {
    String input = "{" + "First Name: "+ FN + ", " +"  Last Name: "+ LN +", "+"   Phone Number: "+ PN + ", " +"  Email: "+ Email +", " +"  Address: "+ Addres + ", " +"  State: "+  State +", "+"  Zip: "+  Zip + ", " +"  LicensePlate: "+ LicensePlate + "}";
    if (rear == maxSize - 1)
        rear = -1;
    queArray[++rear] = input;
    nItems++;
    }

  public String peekFront() {

    return queArray[front++];
}

public String peek() {
    return queArray[front];
}

通过将maxSize ++更改为maxSize = 5固定

1 个答案:

答案 0 :(得分:1)

如果我没有记错的话,这是由于您的maxSize机制引起的。

maxSize永远不会仅设置为maxSize++一次。因此maxSize始终为1。

现在,当已经插入一个Element时,将调用以下代码,因为Rear现在为0,maxSize-1 = 1-1。

if (rear == maxSize - 1) rear = -1; queArray[++rear] = input;

您只是覆盖了数组中唯一的元素。

与其编写自己的基于数组的队列来保存数据,不如考虑为数据使用自定义对象以及已经实现的队列,例如java.util.Queue