问题描述
我有一个 Boolean 类型的 ArrayList,在尝试使用时需要将其作为 boolean[] 进行操作:
I have an ArrayList of type Boolean that requires to be manipulated as a boolean[] as I am trying to use:
AlertDialog builder;
builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() { ... });
然而,虽然我可以创建一个布尔对象数组,但我找不到一种有效的方法来将此对象数组转换为构建器函数调用的原始数组(我能想出的唯一方法是遍历 Object数组并构建一个新的原始数组).
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).
我正在从 ArrayList 中检索我的 Object 数组,如下所示:
I am retrieving my Object array from the ArrayList as follows:
final Boolean[] checkedItems = getBoolList().toArray(new Boolean[getBoolList().size()]);
我可以用我的 ArrayList 做些什么吗?还是我缺少明显的转换/转换方法??
Is there something I can do with my ArrayList? Or is there an obvious casting/conversion method that I am missing??
任何帮助表示赞赏!
推荐答案
你没有遗漏任何东西,唯一的办法就是迭代列表,恐怕
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;
}
编辑(根据 Stephen C 的评论):或者您可以使用第三方工具,例如 Apache Commons ArrayUtils:
Edit (as per Stephen C's comment):Or you can use a third party util such as Apache Commons ArrayUtils:
http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/ArrayUtils.html
这篇关于将布尔对象数组覆盖为布尔原始数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!