search

Home  >  Q&A  >  body text

java - 状态标识(比如0和1),用int好,还是有其他选择了?

状态标识(比如0和1),用int好,还是有其他选择了? 比如short

比如 状态有1和0
int flag=1
short flag=1
这两个那个会好一些了?

PHP中文网PHP中文网2803 days ago919

reply all(4)I'll reply

  • 迷茫

    迷茫2017-04-18 10:53:12

    If you only use it to express status, there is no difference between short and int. If you don’t believe me, you can compile it and look at the bytecode.

    Code

    int flag = 1;
    short flag = 1;

    and code

    int flag = 1;
    int flag = 1;

    The resulting bytecode is exactly the same! You will get the following bytecode,

             0: iconst_1
             1: istore_1
             2: iconst_1
             3: istore_2

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 10:53:12

    Depending on your usage scenario, if it is used for object attributes or SQL parameters, it is best to use Integer. Because you may not initialize it, using int will have a default value of 0 (this 0 may not be what you want)

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 10:53:12

    If the status only has 0 and 1, you can use booleantruefalse) 或者 byte(0 或 1,byte 的范围在 -128 ~ 127);状态如果较多,更推荐用 enum

    reply
    0
  • 迷茫

    迷茫2017-04-18 10:53:12

    Both boolean and int are available. There is no difference.

    reply
    0
  • Cancelreply