1

In TraverseModeSet class of org.opentripplanner.routing.core package, Modes are represented using integer numbers , those are powers of 2. Why?

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;

1 Answer 1

4

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.