Search code examples
javaenumspicasso

Bitwise operators in java


I have copied the following class from Picasso's source code. Actually, I was asking Picasso to not to cache images.

Can any one explain to me these two lines

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.

/** 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;
  }
}

Solution

  • 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).

    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.