Home » Android » java – Coverting a Boolean object array to boolean primitive array?

java – Coverting a Boolean object array to boolean primitive array?

Posted by: admin June 15, 2020 Leave a comment


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() { ... });

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).

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

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??

Any help appreciated!

How to&Answers:

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:



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