假设我有一个类,它包含一个可迭代的对象。现在出于某种原因,我想“包装”这个迭代器,这样当没有更多的东西可以迭代时,我们就不会因为 NoSuchElementException
而崩溃,而是返回 null
。例如,对于 ArrayList,这很容易,因为我可以在我的类上保存一个 index
属性。但对于例如 TreeSet
来说,这就更棘手了,因为据我所知,没有办法使用索引。我如何使用 TreeSet 来实现这一点?有什么方法可以在某处捕获异常吗?
我的持有可迭代对象的类是:
public class MyClass{
TreeSet<Integer> list = new TreeSet<Integer>();
// Do something so that list.iterator() returns null when getting NoSuchElementException
}
我可以这样使用它:
MyClass myObj = new MyClass();
Iterator myIter = myObj.iterator();
iterObj = myIter.next();
while(iterObj != null){
//do stuff
}
当然,我可以在类之外捕获异常,但在多个地方这样做会导致大量的 try 和 catch 语句。
请不要告诉我可以使用 foreach 循环,这在我的应用程序中是不可能的。
编辑:这就是我不能使用hasNext()
的原因:
我有两个迭代器 listA 和 listB。
这是原始算法:
pA = listA.next(); // null if !hasNext()
pB = listB.next(); // null if !hasNext()
while(pA != null && pB != null){
if(pA.docID == pB.docID){
// do stuff
pA = listA.next();
pB = listB.next();
}
else if(pA.docID < pB.docID){
pA = listA.next();
}
else{
pB = listB.next();
}
}
我无法找到使用 hasNext()
实现相同功能的方法。这是一个尝试:
while (listA.hasNext() && listB.hasNext()){
pA = listA.next();
pB = listB.next();
if(pA.docID == pB.docID){
// do stuff
}
else if(pA.docID < pB.docID){
pA = listA.next();
}
else{
pB = listB.next();
}
}
但这显然不是相同的算法,只要我们没有 pA.docID,我们就会在
。有办法解决这个问题吗?listA
或 listB
之一上迭代两次== pB.docID
最佳答案
您似乎希望能够通过返回 null 来进行迭代,而不是抛出异常。虽然这通常不如使用 Ravi 的解决方案那么有利,但我尝试通过一般性地包装迭代器来发挥创意并满足您的需求。
除非这是一项作业,否则请遵循拉维的建议。用 Java 实现控制流是有原因的。通常不鼓励使用此类解决方法。
public class MyClass {
public static class MyIterator<T> {
Iterator<T> defaultIterator;
public MyIterator(Iterator<T> defaultIterator) {
this.defaultIterator = defaultIterator;
}
public T getNext() {
try {
if (defaultIterator.hasNext()) {
return defaultIterator.next();
}
} catch (Exception e) {
// Fall through
}
return null;
}
}
public static void Main(String[] args) {
TreeSet<Integer> list = new TreeSet<>();
MyIterator<Integer> myIterator = new MyIterator<>(list.iterator());
while (myIterator.getNext() != null) {
// do stuff
}
}
}
关于java - 如何包装库类的迭代器以捕获 NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48600085/