简体   繁体   English

java中的按位运算符

[英]Bitwise operators in java

I have copied the following class from Picasso's source code. 我从Picasso's源代码中复制了以下类。 Actually, I was asking Picasso to not to cache images. 实际上,我要求Picasso不要缓存图像。

Can any one explain to me these two lines 任何人都可以向我解释这两行

NO_CACHE(1 << 0), NO_STORE(1 << 1); NO_CACHE(1 << 0), NO_STORE(1 << 1);

I know about bitwise operators, I just want to know why we need them here? 我知道按位运算符,我只想知道为什么我们需要它们?

They have also suppressed PointlessBitwiseExpression warning. 他们还压制了PointlessBitwiseExpression警告。

/** Designates the policy to use when dealing with memory cache. */
@SuppressWarnings("PointlessBitwiseExpression")
public enum MemoryPolicy {

  /** Skips memory cache lookup when processing a request. */
  NO_CACHE(1 << 0),
  /**
   * Skips storing the final result into memory cache. Useful for one-off requests
   * to avoid evicting other bitmaps from the cache.
   */
  NO_STORE(1 << 1);

  static boolean shouldReadFromMemoryCache(int memoryPolicy) {
    return (memoryPolicy & MemoryPolicy.NO_CACHE.index) == 0;
  }

  static boolean shouldWriteToMemoryCache(int memoryPolicy) {
    return (memoryPolicy & MemoryPolicy.NO_STORE.index) == 0;
  }

  final int index;

  private MemoryPolicy(int index) {
    this.index = index;
  }
}

You are asking why we need them? 你在问我们为什么需要它们? This code boils down to: 此代码归结为:

NO_CHACHE(1), NO_STORE(2);

That's it (and just to be complete here: it those constant declarations simply invoke that private constructor of the enum taking an int value). 就是这样(并且只是在这里完成:那些常量声明只是调用枚举的私有构造函数获取int值)。

Thus, the answer to your question is: these shift operations are not needed in any way! 因此,您的问题的答案是:不需要这些转换操作! They carry no additional value (worse: they seem to confuse readers ) 它们没有额外的价值(更糟糕的是:它们似乎让读者感到困惑)

The underlying idea is probably that at some later point some kind of "bit masking" will take place. 潜在的想法可能是在稍后的某个时候会发生某种“比特掩蔽”。 And you know, when you later think in terms of "bits", somebody had the great idea to "think in bits" when declaring those constants, too. 而且你知道,当你后来用“位”来思考时,有人在宣布这些常数时也有一个很好的想法“在位中思考”。

But in that case, something like 但在那种情况下,像

NO_CACHE(0b01), NO_STORE(0b10);

would pretty much do the job, too. 我也会做很多工作。 But even that; 但即便如此; I would find not helpful. 我觉得没用。 If it at all, I would rather put a javadoc there expressing that those constants are intended to be used as "bitwise flags" later on. 如果有的话,我宁愿在那里放一个javadoc,表示这些常量后来打算用作“按位标志”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM