java 将布尔对象数组覆盖为布尔基本数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5615664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:55:40  来源:igfitidea点击:

Coverting a Boolean object array to boolean primitive array?

javaandroidarraysobjectboolean

提问by Kaiesh

I have an ArrayList of type Boolean that requires to be manipulated as a boolean[] as I am trying to use:

我有一个 Boolean 类型的 ArrayList 需要在我尝试使用时将其作为 boolean[] 进行操作:

AlertDialog builder;
builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() { ... });

However, while I can create a Boolean object array, I cannot find an efficient way to covert this object array to a primitive array that the builder function calls for (the only method I can come up with is to iterate over the Object array and build a new primitive array).

但是,虽然我可以创建一个 Boolean 对象数组,但我找不到一种有效的方法来将此对象数组转换为 builder 函数调用的原始数组(我能想到的唯一方法是遍历 Object 数组并构建一个新的原始数组)。

I am retrieving my Object array from the ArrayList as follows:

我正在从 ArrayList 检索我的 Object 数组,如下所示:

final Boolean[] checkedItems = getBoolList().toArray(new Boolean[getBoolList().size()]);

Is there something I can do with my ArrayList? Or is there an obvious casting/conversion method that I am missing??

我可以用我的 ArrayList 做些什么吗?还是我缺少明显的转换/转换方法?

Any help appreciated!

任何帮助表示赞赏!

回答by edwardsmatt

You aren't missing anything, the only way to do it is to Iterate over the list I'm afraid

你没有遗漏任何东西,唯一的方法就是遍历列表恐怕

An (Untested) Example:

一个(未经测试的)示例:

private boolean[] toPrimitiveArray(final List<Boolean> booleanList) {
    final boolean[] primitives = new boolean[booleanList.size()];
    int index = 0;
    for (Boolean object : booleanList) {
        primitives[index++] = object;
    }
    return primitives;
}

Edit (as per Stephen C's comment): Or you can use a third party util such as Apache Commons ArrayUtils:

编辑(根据 Stephen C 的评论):或者您可以使用第三方工具,例如 Apache Commons ArrayUtils:

http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/ArrayUtils.html

http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/ArrayUtils.html

回答by ColinD

Using Guava, you can do boolean[] array = Booleans.toArray(getBoolList());.

使用番石榴,你可以做到boolean[] array = Booleans.toArray(getBoolList());