有什么更好的方法来修改这段代码[重构]

发布于 2025-01-07 18:16:22 字数 1486 浏览 1 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

独孤求败 2025-01-14 18:16:22

你的两条指令在 if 两边都是一样的!我怀疑你粘贴错了东西。让我们假设它们是不同的("Y""N"):) 您可以简单地使用 三元运算符

while (vIter.hasNext()) {
    Long actId =(Long)vIter.next();
    vRetActIds.put(actId, actId == -1 ? "N" : "Y");
}

编辑:从您的评论来看,您似乎确实想将值设置为 'N ' 每次?在这种情况下,您根本不需要 if...

while (vIter.hasNext()) {
    vRetActIds.put((Long)vIter.next(), "N");
}

Your two instructions are the same on both sides of the if! I suspect you pasted something wrong. Let's assume they're different ("Y" and "N") :) You can write it simply using the ternary operator:

while (vIter.hasNext()) {
    Long actId =(Long)vIter.next();
    vRetActIds.put(actId, actId == -1 ? "N" : "Y");
}

EDIT: From your comments, it seems like you actually want to set the value to 'N' every time? In that case, you don't need the if at all...

while (vIter.hasNext()) {
    vRetActIds.put((Long)vIter.next(), "N");
}
她说她爱他 2025-01-14 18:16:22

如果我们可以假设您在新的java中使用某种集合,那么这样的东西会更简洁并且不会因空指针而崩溃?

Long MINUS_ONE = Long.valueOf(-1);
while (Long actId : vIter) 
{
    vRetActIds.put(actId, MINUS_ONE.equals(actiId) ? "N" : "Y");
}

If we can assume that you are using a Collection of some sort in the new java, something like this would be more concise and won't crash due to null pointers?

Long MINUS_ONE = Long.valueOf(-1);
while (Long actId : vIter) 
{
    vRetActIds.put(actId, MINUS_ONE.equals(actiId) ? "N" : "Y");
}
金兰素衣 2025-01-14 18:16:22

三元条件语句就可以了。

vRetActIds.put(actId, actiId == -1 ? "N" : "Y");

Ternary conditional statement would be fine.

vRetActIds.put(actId, actiId == -1 ? "N" : "Y");
通知家属抬走 2025-01-14 18:16:22

假设您从列表之类的地方获取迭代器:

List<Long> list;
Iterator<Long> vIter = list.iterator();

如果是这种情况(并且它或类似的东西几乎必须是这种情况),那么您可以完全放弃迭代器并使您的代码更易于阅读, 因此:

for (Long actId: list)
    vRetActIds.put(actId, "N");

Let's assume you're getting your iterator from somewhere like a List:

List<Long> list;
Iterator<Long> vIter = list.iterator();

If that's the case (and it, or something like it, almost has to be the case), then you can forgo the iterator entirely and make your code much easier to read, thus:

for (Long actId: list)
    vRetActIds.put(actId, "N");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文