![](/img/trans.png)
[英]Correct use of AtomicReference.compareAndSet for a stack implementation
[英]Correct implementation of stack behavior
我有一個旨在將堆棧基礎實現為Web瀏覽器url的類。
預期的行為如下所示:如果用戶在地址欄中鍵入URL,則將清除前向堆棧。 如果用戶單擊“后退”按鈕,則當前URL(在地址欄中)將被推入前向堆棧。 彈出堆棧,然后將彈出的URL放在地址欄中。 如果后堆棧為空,則什么也不會發生。 如果用戶單擊前進按鈕,則當前URL(在地址欄中)將被推入后退堆棧。 彈出前向堆棧,然后將彈出的URL放在地址欄中。如果向后堆棧為空,則不會發生任何事情。
基本上,我在處理后堆棧方面遇到了問題。 每次調用后堆棧塊時,當前URL都會被壓入前堆棧。 雖然此行為對於后推堆棧的一推是正確的,但在后推堆棧不再向后移動時,這是意料之外的(示例:Google.com [back stack call] Google.com,將Google.com兩次推入前推堆棧) 。
我無法考慮不允許發生這種情況的邏輯。 必須多次向前推送堆棧才能僅向上移動一個網頁,這顯然是不正確的行為。
在保持我的代碼核心完整的同時,有什么建議嗎?
public class BrowserStack {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
// the current URL
String url = null;
Stack<String> forward = new Stack<String>();
Stack<String> back = new Stack<String>();
String input;
System.out.println("Type a combination of URLs, or the > or < symbol.\nType 'q' to quit.");
while (true) {
input = s.next();
if (input.equals("q")) {
System.out.println("Bye");
return;
}
if (input.equals("<")) {
try {
forward.push(url); //unintended behavior happens here
url = back.pop();
} catch (EmptyStackException e) {
}
}
else if (input.equals(">")) {
try {
back.push(url);
url = forward.pop();
} catch (EmptyStackException e) {
}
}
else {
if (url != null)
back.push(url);
url = input;
forward.clear();
}
System.out.println("Current webpage [" + url + "]");
}
}
}
交換您的推送/彈出順序,以便在推送到堆棧之前退出try / catch:
if (input.equals("<")) {
try {
String temp = url;
url = back.pop();
forward.push(temp); // this only executes if the last line completed unexceptionally
} catch (EmptyStackException e) {
}
}
但是,更根本不引發異常,而是在彈出之前進行檢查會更正確:
if (input.equals("<")) {
if (!back.isEmpty());
forward.push(url);
url = back.pop();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.