英文:
Java switch case breaks method
问题
我有一个简单的 switch case。和一个简单的方法。
问题是,对于 switch case 中的某些字符串,调用相同的方法时,该方法返回不同的结果。
case: "list.all" 调用 listAll() 方法
导致以下输出
listAll - 开始
处理器:process.listAll 键::06.2003,值:69.0
处理器:process.listAll 键::08.2003,值:88.0
listAll - 结束
case: "list" 调用 listAll() 方法(与之前相同的方法)
但现在结果是
listAll - 开始
listAll - 结束
我不太清楚为什么 "switch" 影响方法的结果。
有人能解释一下吗?
@Override
public void process(String action, String v) {
switch(action)
{
case ("delete"):
this.delete(action, v);
break;
case ("list"):
this.listAll();
break;
case ("list.all"):
this.listAll();
break;
default:
this.upsert(action,v);
} // end switch
context.commit();
} // end process
public void listAll() {
System.out.println("listAll - 开始");
KeyValueIterator<String, WrapperMinMax> iter = this.kvStore.all();
while (iter.hasNext()) {
KeyValue<String, WrapperMinMax> entry = iter.next();
System.out.printf("处理器:process.listAll 键:%s,值:%s\n", entry.key.toString(), entry.value.getMax());
}
iter.close();
System.out.println("listAll - 结束");
}
英文:
I have a simple switch case. And a simple method.
The problem is, for some strings in the switch case, while calling the same method.
The method returns a diffrent result.
case: "list.all" is calling listALL()
results in the follwing output
listAll - start
processor: process.listAll key: :06.2003, value: 69.0
processor: process.listAll key: :08.2003, value: 88.0
listAll - end
case: "list" is calling listALL() .. the same method as before
but now the result is
listAll - start
listAll - end
Not clear to me why the "switch" impacts the result of the method.
Can someone explain this please?
@Override
public void process(String action, String v) {
switch(action)
{
case ("delete"):
this.delete(action, v);
break;
case ("list"):
this.listAll();
break;
case ("list.all"):
this.listAll();
break;
default:
this.upsert(action,v);
} // end switch
context.commit();
} // end process
public void listAll() {
System.out.println("listAll - start");
KeyValueIterator<String, WrapperMinMax> iter = this.kvStore.all();
while (iter.hasNext()) {
KeyValue<String, WrapperMinMax> entry = iter.next();
System.out.printf("processor: process.listAll key: :%s, value: %s\n", entry.key.toString(), entry.value.getMax());
}
iter.close();
System.out.println("listAll - end");
}
答案1
得分: 3
因为在这里 this.kvStore.all();
,你没有创建一个新的迭代器,而是重用了一个已经超出范围的迭代器。
因此,调用 while
循环后,一次性使用了所有的迭代,第二次运行时,iter.hasNext()
返回 false
。
英文:
I think because here this.kvStore.all();
you are not creating new iterator but reuse the one that has exceeded already.
Hence calling while
loop once eats up all the iterations and the second run gets iter.hasNext()
returning false
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论