I was walking through some code and came across these lines:
public final static int CM_VALUE = 0x200;
public final static Integer CM = new Integer(CM_VALUE);
D开发者_如何学JAVAo anyone know why the author held the value in hex before passing it back to Integer
? Does doing it this way add any benefits to the code?
My vote is for convenience. The Author may have needed to use it in a Collection and wanted to init these statics at class init time for speed.
...tons of speculation on this one!
This depends on the usage of the value of CM. It could add clarity if it was being used as a bitmask or some other bit related operation. It makes no difference to the compiler input what base value a hard coded value is entered as.
However it is strange that the author would then convert it to an Integer object instead of using it as a plain int.
Hexadecimal literals represent exactly the same bits as their decimal counterparts.
So no, it's not really any better for the computer.
Depending on the use it might be better readable for the developer, however.
For example this:
private final int FLAG_A = 0x01;
private final int FLAG_B = 0x02;
private final int FLAG_C = 0x04;
private final int FLAG_D = 0x08;
private final int FLAG_E = 0x10;
private final int FLAG_F = 0x20;
private final int FLAG_G = 0x40;
private final int FLAG_H = 0x80;
is probably easier to grasp than this (which is equivalent, however!):
private final int FLAG_A = 1;
private final int FLAG_B = 2;
private final int FLAG_C = 4;
private final int FLAG_D = 8;
private final int FLAG_A = 16;
private final int FLAG_B = 32;
private final int FLAG_C = 64;
private final int FLAG_D = 128;
The value might be a bit mask or might be an externally defined constant. In the case of a bit mask, it's best to store them as hex values to make it more obvious what you are doing. If it was an external constant then it makes sense to use the same base as the definition to make finding any typos easier.
Using hexadecimal is useful when you want to deal with binary representation, so 0x200
is simpler than the binary representation 1000000000
.
Maybe the place where the programmer who wrote this has a rule that there must be no hard-coded constants in source code, and that constants should always be used by defining a static final variable for them. In my opinion, such a rule can be good, but in this example it has probably been taken too far.
Note that in general it's better to never use new Integer(...)
, use Integer.valueOf(...)
instead. Class Integer
can reuse objects if you use valueOf
rather than explicitly creating a new Integer
object.
public final static int CM_VALUE = 0x200;
public final static Integer CM = Integer.valueOf(CM_VALUE);
Even better, just use autoboxing, which make it even less necessary to have CM_VALUE
:
public final static Integer CM = 0x200;
精彩评论