You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何验证CarTypeEnum枚举常量的任意组合是否合法?

问题描述

现有Java枚举CarTypeEnum定义如下:

public enum CarTypeEnum {
    SEDAN(1),
    CABRIO(2),
    ELECTRIC(4),
    ...;

    private final int carType;

    private CarTypeEnum(int carType) {
        this.carType = carType; // 注:原代码中`this.carype`存在拼写错误,已修正
    }

    public int getCarType() {
        return carType;
    }
}

包含carType整型字段的Car类:

public class Car {
    private String id;
    private int carType;
}

目前已实现校验单个枚举值是否合法的方法:

public boolean isValid(int carType) {
   return carType == CarTypeEnum.SEDAN.getCarType()
      || carType == CarTypeEnum.CABRIO.getCarType()
      || carType == CarTypeEnum.ELECTRIC.getCarType();
}

需求:实现校验逻辑,确保carType的整型值可以是CarTypeEnum中定义的枚举常量的任意组合(比如1、2、3(2+1)、4、5(4+1)、6(4+2)、7(4+2+1)等)。


解决方案

由于枚举值都是2的幂次(1=20、2=21、4=2^2),它们的二进制位互不重叠,组合值本质是位掩码叠加,可以通过以下方式实现校验:

方法1:动态计算合法掩码校验

public boolean isValidCombination(int carType) {
    // 计算所有合法枚举值的位掩码总和
    int validMask = 0;
    for (CarTypeEnum type : CarTypeEnum.values()) {
        validMask |= type.getCarType();
    }
    // 核心逻辑:输入值的所有有效位都在合法掩码范围内
    return (carType & validMask) == carType;
}

方法2:提前定义全局掩码(更高效)

在枚举类中预定义全局掩码常量,避免每次校验都遍历枚举:

public enum CarTypeEnum {
    SEDAN(1),
    CABRIO(2),
    ELECTRIC(4),
    ...;

    private final int carType;
    // 预计算所有合法类型的位掩码总和
    public static final int ALL_TYPES_MASK = Arrays.stream(values())
            .mapToInt(CarTypeEnum::getCarType)
            .reduce(0, (a, b) -> a | b);

    private CarTypeEnum(int carType) {
        this.carType = carType;
    }

    public int getCarType() {
        return carType;
    }
}

对应的校验方法简化为:

public boolean isValidCombination(int carType) {
    return (carType & CarTypeEnum.ALL_TYPES_MASK) == carType;
}

逻辑说明

按位与运算(carType & validMask) == carType的作用是:如果输入值的所有二进制位都属于合法掩码包含的位,说明输入值是枚举常量的合法组合;反之则存在非法的位,属于无效值。

内容的提问来源于stack exchange,提问作者cd491415

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 10:48:17