-1

I saw a java class whose int variables are assingned with values of 2's power. Is there any advantages by doing like this?

private static final int MODE_BICYCLE = 1;

private static final int MODE_WALK = 2;

private static final int MODE_CAR = 4;

private static final int MODE_BUS = 16;

private static final int MODE_TRAM = 32;

private static final int MODE_SUBWAY = 64;

private static final int MODE_RAIL = 128;

private static final int MODE_FERRY = 256;

private static final int MODE_CABLE_CAR = 512;

private static final int MODE_GONDOLA = 1024;

private static final int MODE_FUNICULAR = 2048;

private static final int MODE_TRAINISH = MODE_TRAM | MODE_RAIL | MODE_SUBWAY | MODE_FUNICULAR | MODE_GONDOLA;

private static final int MODE_BUSISH = MODE_CABLE_CAR | MODE_BUS;

private static final int MODE_TRANSIT = MODE_TRAINISH | MODE_BUSISH | MODE_FERRY;

private static final int MODE_ALL = MODE_TRANSIT | MODE_WALK | MODE_BICYCLE;

private int modes = 0;
assylias
  • 321,522
  • 82
  • 660
  • 783
Anuraj
  • 2,551
  • 21
  • 26
  • 2
    This is some crazy bitwise ORing – TheLostMind Oct 29 '15 at 10:03
  • 1
    The "correct" way would be to use an EnumSet. But even the JDK developers sometimes do it: http://stackoverflow.com/questions/22596495/justification-for-using-a-bitfield-instead-of-enumset-in-modern-java-8-api – assylias Oct 29 '15 at 10:11

2 Answers2

1

As you posted the advantage is that you can put in or your variables. For example:

private static final int MODE_BUSISH = MODE_CABLE_CAR | MODE_BUS;

This can't be done if you don't choose powers of 2.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
0

So that we can combine them with the bitwise-or operator and then separate them later. For instance, MODE_TRAINISH = MODE_TRAM | MODE_RAIL | MODE_SUBWAY | MODE_FUNICULAR | MODE_GONDOLA;

If we later want to see if e.g. is included in the set, we can just do mode & MODE_TRAM and see if it's non-zero.

In other words, we're representing a set of values in a single integer. This is quite space-efficient, and it's also time-efficient to test for set membership (bitwise-and), add elements (bitwise-or), or remove elements (bitwise-and with complement).

Anuraj
  • 2,551
  • 21
  • 26
  • 3
    Or, they could have used a `BitSet`... – Mena Oct 29 '15 at 10:04
  • 3
    I would not expect to see this kind of code in general usage Java code. While that's a neat "trick" and can be a good solution in some very specific cases, it has no place in "normal" Java code. – Kayaman Oct 29 '15 at 10:06
  • have you thought about the performance benefit of having 4 local variables instead of 1 variable and using bitwise OR? – TheLostMind Oct 29 '15 at 10:12
  • In addition you are limited to only 31 variables if you are using `int` and 62 if you are using `long`. Depending on the requirement this could end in a unneccessary refactoring pretty quickly. – SomeJavaGuy Oct 29 '15 at 10:16