Java: Enum vs. Int

前端 未结 9 2327
野的像风
野的像风 2020-11-27 14:11

When using flags in Java, I have seen two main approaches. One uses int values and a line of if-else statements. The other is to use enums and case-switch statements.

<
9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 14:52

    You may even use Enums to replace those bitwise combined flags like int flags = FLAG_1 | FLAG_2;

    Instead you can use a typesafe EnumSet:

    Set flags = EnumSet.of(FlagEnum.FLAG_1, FlagEnum.FLAG_2);
    
    // then simply test with contains()
    if(flags.contains(FlagEnum.FLAG_1)) ...
    

    The documentation states that those classes are internally optimized as bit vectors and that the implementation should be perform well enough to replace the int-based flags.

提交回复
热议问题