BitSet

作者: jumper996 | 来源:发表于2020-03-07 00:26 被阅读0次
    public static <E extends Enum<E>> int encode(EnumSet<E> set) {
        int ret = 0;
    
        for (E val : set) {
            ret |= 1 << val.ordinal();
        }
    
        return ret;
    }
    
    private static <E extends Enum<E>> EnumSet<E> decode(int code,
                                                         Class<E> enumType) {
        try {
            E[] values = (E[]) enumType.getMethod("values").invoke(null);
            EnumSet<E> result = EnumSet.noneOf(enumType);
            while (code != 0) {
                int ordinal = Integer.numberOfTrailingZeros(code);
                code ^= Integer.lowestOneBit(code);
                result.add(values[ordinal]);
            }
            return result;
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(ex);
        } catch (InvocationTargetException ex) {
            throw (RuntimeException) ex.getCause();
        } catch (NoSuchMethodException ex) {
            throw new RuntimeException(ex);
        }
    }
    

    相关文章

      网友评论

          本文标题:BitSet

          本文链接:https://www.haomeiwen.com/subject/nuftdhtx.html