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

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

问题描述

我有一个 EnumSet 并想回来,来回向/从布尔元的数组转换。如果工作得更好,我可以用一个 列表<工作/ code> 而不是一个阵列,和/或 布尔 对象,而不是布尔元。

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:


  • 布尔或布尔对整数(显然)

  • 我要枚举的所有成员重新presented,以 TRUE 为包括在每个枚举元素的 EnumSet 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)

推荐答案

要做到这一点,你会写基本

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 _ 下方创建。

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天全站免登陆