Java三元运算符和设置循环索引值

发布于 2024-11-09 09:17:09 字数 518 浏览 6 评论 0原文

我有一个循环遍历 ArrayList 的 for 循环。

如果 for 循环中满足条件:

  • 我从 ArrayList 中删除当前元素
  • 减少 ArrayList 局部变量的大小 减少
  • for 循环的索引,如下所示,检查确保它们永远不会低于零。

我们刚刚删除了 ArrayList 的最后一个元素的情况:

i = (i > 0) ? i-- : i;

我的问题是,当 i > 时,上面的方法不会将 i 减少 1。 0.我已经无数次使用三元运算符,但从未见过这种行为。我测试过 i 确实是 > 0 并且 i-- 部分正在被调用。它根本没有减少 i 的值。删除 0 值检查并简单地运行 i--; 确实会按预期减少 i 。

EDIT2:好吧,有人编辑了我的上一次编辑,我在其中提到我在这种情况下特别不使用 ListIterator,因为循环本身对性能敏感,位于 Android 代码的关键部分。

I have a for loop looping through an ArrayList.

If a condition is met in the for loop:

  • I remove the current element from the ArrayList
  • reduce the size of the ArrayList local variable
  • reduce the for loop's index like so, checking to ensure that they never go below zero.

A case where we have just removed the last element of the ArrayList:

i = (i > 0) ? i-- : i;

My problem is that the above does not reduce i by 1 when i > 0. I've used ternary operators countless times, but never seen this behavior. I've tested that i is indeed > 0 and that the i-- section is being called. It simply isn't reducing the value of i. Removing the 0 value check and simply running i--; does indeed reduce i as expected.

EDIT2: Ok, well someone edited out my last edit where I mentioned that I am specifically NOT using a ListIterator in this case due to the performance sensitive nature of the loop itself, being in a critical portion of Android code.

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

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

发布评论

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

评论(8

风吹雨成花 2024-11-16 09:17:09

i-- 递减 i,但返回原始值。

i = i-- 会递减 i,然后将其赋给其原始值。

您应该使用i - 1

i-- decrements i, but returns the original value.

i = i-- will decrement i, then assign it to its original value.

You should use i - 1.

み格子的夏天 2024-11-16 09:17:09

最小修复:

您可能会遇到这样的问题:

for (int i = 0; i < l.size(); i++) {         <--------------------------------.
    if (cond) {                                                               |
        l.remove(i);                                                          |
        i--;              // even if i == -1, it will be set back to 0 here --'
    }
}

向后迭代:

另一个常见的解决方案是向后迭代,如下所示:

for (int i = l.size() - 1; i >= 0; i--) {
    if (cond) {
        l.remove(i);
    }
}

使用 ListIterator(除非对性能至关重要):

但是,使用 ListIterator更好

Iterator<String> iter = l.iterator();
while (iter.hasNext()) {
    if (shouldRemove(iter.next())
        iter.remove();
}

Smallest fix:

You may be after something like this:

for (int i = 0; i < l.size(); i++) {         <--------------------------------.
    if (cond) {                                                               |
        l.remove(i);                                                          |
        i--;              // even if i == -1, it will be set back to 0 here --'
    }
}

Backward iteration instead:

Another common solution is to iterate backwards, like this:

for (int i = l.size() - 1; i >= 0; i--) {
    if (cond) {
        l.remove(i);
    }
}

Using ListIterator (unless highly performance critical):

However, you're even better off with a ListIterator:

Iterator<String> iter = l.iterator();
while (iter.hasNext()) {
    if (shouldRemove(iter.next())
        iter.remove();
}
扮仙女 2024-11-16 09:17:09

你尝试过吗?:

i = (i > 0) ? --i : i;

通过预减,你应该解决所有问题。

Did you try?:

i = (i > 0) ? --i : i;

With pre-decrement you should solve all your problems.

琉璃梦幻 2024-11-16 09:17:09

i = i-- 这样的赋值(对于 i > 0 会发生这种情况)根本没有意义:您到底在这里期望什么?使用以下内容代替:

i = (i > 0) ? i - 1 : i;

或者更好:

if (i > 0)
    i--;

Having an assignment such as i = i-- (which happens for i > 0) simply doesn’t make sense: what exactly are you expecting here? Use the following instead:

i = (i > 0) ? i - 1 : i;

Or, even better:

if (i > 0)
    i--;
白况 2024-11-16 09:17:09

做正确的事情:使用迭代器循环数组列表并在迭代时安全地删除项目。

Do the right thing: use an iterator to loop over your array list and safely remove items while iterating.

情未る 2024-11-16 09:17:09

您所描述的算法对于您尝试执行的操作来说是一个糟糕的策略:从 ArrayList 中删除元素是一个 O(n) 操作,因此在一般情况下将其应用于整个 ArrayList 是 O(n^2) 。

更好的策略:

  • 创建一个新的空 ArrayList
  • 循环遍历原始 ArrayList 一次,然后仅将要保留的元素添加到新的 ArrayList

这是 O(n),并且实际上会是更简单的代码(您不必担心摆弄循环边界等)

The algorithm you have described is a bad strategy for what you are trying to do: removing an element from an ArrayList is an O(n) operation so applying this to the entire ArrayList is O(n^2) in the general case.

A much better strategy:

  • Create a new empty ArrayList
  • Loop once through the original ArrayList, and add only the elements you want to keep to the new ArrayList

This is O(n), and will actually be simpler code (you don't have to worry about fiddling with the loop bounds etc.)

樱娆 2024-11-16 09:17:09

考虑不要将三元运算符与 noop 一起使用。

如果(i>0)
{
- 我
}

准确描述了您想要的功能(基于您的示例)。

Consider not using a ternary operator with a noop.

if (i > 0)
{
--i
}

exactly describes the functionality you want (based on your example).

韬韬不绝 2024-11-16 09:17:09

正如其他人所说,i-- 递减 i 并返回原始值,这意味着您的代码将执行递减,但随后立即将其设置回原始值。

您可以将其更改为 --i,在这种情况下,将返回递减的值,但无论哪种方式,您都在使用 -- 进行不必要的工作,因为它必须设置 i,返回新值,然后再次将 i 设置为新值。

你最好只做 i-1 ,它不会两次设置 i 的值:

i = (i > 0) ? i-1 : i;

话虽如此,因为三元的 false 选项不会'不做任何事情,您可能最好使用简单的 if()

if(i > 0) { i--; }

它更容易阅读,无论 -- 的方向如何,并且无论结果如何,都不进行任何不必要的处理。

As others have said, i-- decrements i and returns the original value, meaning that your code would have performed the decrement, but then immediately set it back to its original value.

You could switch it around to be --i, in which case the decremented value will be returned, but either way you're doing un-necessary work with the --, because it has to set i, return the new value, and then set i again to the new value.

You'd be better off just doing i-1, which won't set the value of i twice:

i = (i > 0) ? i-1 : i;

All that said, since the false option of the ternary doesn't do anything, you'd probably be better of just using a straightforward if():

if(i > 0) { i--; }

It's easier to read, doesn't matter which way round the -- goes, and doesn't do any unnecessary processing, whatever the result.

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