Java | =运算符问题 [英] Java |= operator question

查看:77
本文介绍了Java | =运算符问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有关这个奇怪的操作符 | = 的帮助。你能解释一下这段代码的作用吗?

I need help about this strange operator |=. Can you explain to me what this code does ?

@Override
public boolean addAll(Collection<? extends E> c) {
    boolean result = false;
    for (E e : c) {
        result |= add(e);
    }
    return result;
}


推荐答案

代码正在添加所有成员使用 add()方法返回集合 c>,表示 add()是否成功。 addAll 方法的作用是返回 true 如果任何添加成功且 false 如果所有这些都失败了。 (这对我来说似乎很奇怪,因为如果所有的添加成功,我只会返回 true ,但我离题了。)

The code is adding all members of a Collection using the add() method which returns a boolean, indicating if the add() succeeded or not. What the addAll method does is return true if any of the adds succeeded and false if all of them failed. (This does seems odd to me, since I'd only return true if all the adds were succesful, but I digress.)

所以你可以这样做:

@Override
public boolean addAll(Collection<? extends E> c) {
    boolean result = false;
    for (E e : c) {
        if (add(e)) {
           result = true;
        }
    }
    return result;
}

但是你可以对结果变量更直接:

But that's a little verbose as you can act on the result variable more directly:

@Override
public boolean addAll(Collection<? extends E> c) {
    boolean result = false;
    for (E e : c) {
        result = add(e) || result;
    }
    return result;
}

所以我们逻辑上正在对<$ c $的旧值进行OR运算c>结果,返回值为 add 以获取新值。 (注意 - 我们希望结果位于 || 的右侧;这是因为 || shortcircuits并且如果左侧<$ c,则无需检查 || 的右侧$ C>真)。因此,如果添加(e)结果是另一种方式,它不会评估右侧 - 即不运行 add()方法 - 一旦结果 为真 。)

So we're logically OR-ing the old value of result with the return value of add to get the new value. (Note - we want result to be on the right hand side of the ||; this is because || "shortcircuits" and doesn't bother checking the right hand side of an || if the left side is true). So if add(e) and result were the other way around it would not evaluate the right hand side - i.e. not run the add() method - once result were true.)

编写该方法的人决定尽可能简洁,以便更改:

Whoever wrote that method decide they wanted to be as terse as possible so they changed:

result = add(e) || result;

to:

result |= add(e);

与以下内容相同:

result = result | add(e);

| 运算符是一个按位OR ,它与逻辑OR不同,除了布尔值效果基本相同,唯一的区别是 | 没有上面提到的短路行为。

The | operator is a bitwise OR which is not the same a logical OR, except for booleans where the effect is basically the same, the only difference being the | does not have the shortcircuit behaviour mentioned above.

Java中没有 || = 语法,这就是使用按位OR的原因,尽管它可能会有上面提到的相同的短路问题。

There is no ||= syntax in Java which is why the bitwise OR is being used, although even if it did it would probably have the same shortcircuit problem mentioned above.

这篇关于Java | =运算符问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆