問(wèn)題描述
也就是說(shuō),如何在不移除迭代器的情況下獲取下一個(gè)元素?因?yàn)槲铱赡芟胍部赡懿幌雱h除它,具體取決于它的內(nèi)容.我有一個(gè)文件掃描器,我在其中使用 Scanner next() 方法迭代 XML 標(biāo)記.
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.
提前致謝.
推薦答案
參見(jiàn) this 答案是更有效的解決方案.
See this answer for a more efficient solution.
這是一個(gè)非常丑陋的解決方案,但是您可以圍繞 Scanner
創(chuàng)建一個(gè)包裝類,它保留兩個(gè)內(nèi)部 Scanner
對(duì)象.您可以通過(guò)將第二個(gè)掃描儀放在另一個(gè)前面來(lái)獲得 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
這是一個(gè)非常基本的解決方案(只是為了讓您了解我在說(shuō)什么)并且沒(méi)有實(shí)現(xiàn)您需要的所有內(nèi)容(但您只需要實(shí)現(xiàn)您將使用的那些部分).(此外,這是未經(jīng)測(cè)試的,因此請(qǐng)謹(jǐn)慎對(duì)待).
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;
}
}
這篇關(guān)于我如何“偷看"?Java Scanner 的下一個(gè)元素?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!