問題描述
也就是說,如何在不移除迭代器的情況下獲取下一個元素?因為我可能想也可能不想刪除它,具體取決于它的內容.我有一個文件掃描器,我在其中使用 Scanner next() 方法迭代 XML 標記.
That is, how do I get the next element of the iterator without removing it? As I may or may not want to remove it depending on its content. I have a file scanner where I iterate over XML tags using the Scanner next() method.
提前致謝.
推薦答案
參見 this 答案是更有效的解決方案.
See this answer for a more efficient solution.
這是一個非常丑陋的解決方案,但是您可以圍繞 Scanner
創建一個包裝類,它保留兩個內部 Scanner
對象.您可以通過將第二個掃描儀放在另一個前面來獲得 peek()
功能
This is a very ugly solution, but you can create a wrapper class around Scanner
which keeps two internal Scanner
objects. You can get peek()
functionality by having the second scanner one ahead of the other
這是一個非常基本的解決方案(只是為了讓您了解我在說什么)并且沒有實現您需要的所有內容(但您只需要實現您將使用的那些部分).(此外,這是未經測試的,因此請謹慎對待).
This is a very basic solution (just to give you an idea of what I'm talking about) and doesn't implement all that you would need (but you would only need to implement those parts you would use). (also, this is untested, so take it with a grain of salt).
import java.util.Scanner;
public class PeekableScanner
{
private Scanner scan1;
private Scanner scan2;
private String next;
public PeekableScanner( String source )
{
scan1 = new Scanner(source);
scan2 = new Scanner(source);
next = scan2.next();
}
public boolean hasNext()
{
return scan1.hasNext();
}
public String next()
{
next = (scan2.hasNext() ? scan2.next() : null);
return scan1.next();
}
public String peek()
{
return next;
}
}
這篇關于我如何“偷看"?Java Scanner 的下一個元素?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!