在EnumSet和布尔值数组之间转换 [英] Convert between EnumSet and array of boolean values

查看:188
本文介绍了在EnumSet和布尔值数组之间转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 EnumSet ,并希望来回转换为布尔基元数组。如果效果更好,我可以使用 列表 代替数组,和/或 布尔值 对象而不是布尔基元。

I have an EnumSet and want to convert back-and-forth to/from an array of boolean primitives. If it works better, I could work with a List instead of an array, and/or Boolean objects rather than boolean primitives.

enum MyEnum { DOG, CAT, BIRD; }
EnumSet enumSet = EnumSet.of( MyEnum.DOG, MyEnum.CAT ); 

另一端要获得的是一个如下所示的数组:

What I want to get on the other end is an array that looks like this:

[TRUE, TRUE, FALSE]

这里的问题与此类似,将EnumSet转换为整数数组。差异:

This Question here is similar to this one, Convert an EnumSet to an array of integers. Differences:


  • 布尔值或布尔值与整数(显然)

  • 我想要枚举枚举的所有成员,包含在 EnumSet TRUE c $ c>和 FALSE ,用于从 EnumSet 中排除的每个元素。另一个问题的数组只包含 EnumSet 中找到的项目。 (更重要的是)

  • boolean or Boolean versus integers (obviously)
  • I want all members of the enum to be represented, with a TRUE for each enum element included in the EnumSet and a FALSE for each element that is excluded from the EnumSet. The other Question’s array includes only the items found in the EnumSet. (more importantly)

推荐答案

b
$ b

To do that you'd basically write

MyEnum[] values = MyEnum.values(); // or MyEnum.class.getEnumConstants()
boolean[] present = new boolean[values.length];
for (int i = 0; i < values.length; i++) {
  present[i] = enumSet.contains(values[i]);
}

走向另一个方向,从布尔数组 present 以上创建的 enumSet _

Going the other direction, from boolean array present created above to enumSet_ created below.

EnumSet<MyEnum> enumSet_ = EnumSet.noneOf ( MyEnum.class );  // Instantiate an empty EnumSet.
MyEnum[] values_ = MyEnum.values ();
for ( int i = 0 ; i < values_.length ; i ++ ) {
    if ( present[ i ] ) {  // If the array element is TRUE, add the matching MyEnum item to the EnumSet. If FALSE, do nothing, effectively omitting the matching MyEnum item from the EnumSet.
        enumSet_.add ( values_[ i ] );
    }
}

这篇关于在EnumSet和布尔值数组之间转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆