Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The method toArray(T[]) in the type ArrayList<Boolean> is not applicable for the arguments (boolean[])

I write a function to get boolean array, from arraylist<boolean> to boolean array but I get the error:

The method toArray(T[]) in the type ArrayList is not applicable for the arguments (boolean[])

ArrayList<Boolean> fool = new ArrayList<Boolean>();

for (int i = 0; i < o.length(); i++) {
    if (Integer.parseInt(o.substring(i, i + 1)) == 1) {
        fool.add(true);
    } else {
        fool.add(false);
    }
}

boolean[] op = fool.toArray(new boolean[fool.size()]);

if I change the type boolean[]op to Boolean[]op, that is work, but I need boolean[]..

So how can i get the boolean array?

like image 303
chanjianyi Avatar asked Dec 26 '22 06:12

chanjianyi


2 Answers

Primitive types cannot be used in generics. In order for the array to match the type signature of T[], you must use the Boolean wrapper class just as you did in the ArrayList's declaration, even if you don't want the final array to be of that type:

Boolean[] op = fool.toArray(new Boolean[fool.size()]);

There is no way to get an array of primitive booleans using generics, and autoboxing or casting does not work with arrays (e.g. it is impossible to assign arrays of primitive types to arrays of the wrapper types and vice-versa). The only way to get the array you want is to do it the hard way, with loops:

boolean[] op = new boolean[fool.size()];

for(int n = 0; n < temp.length; n++)
{
     //autoboxing implicitly converts Boolean to boolean
     op[n] = fool.get(n); 
}

This can probably be accomplished much more elegantly using the map construct in Java 8.

On a personal note, the fact that generics don't work for primitives is one of the few things about java that honestly really frustrates me. I'm not going to argue with the designers, but having to write seven different functions just to do the same thing to arrays of different types seems to defy the whole point of adding a generics feature to the language in the first place. Just look at the java.util.Arrays class; having to write this kind of code is enough to make me want to switch to C++.

like image 149
ApproachingDarknessFish Avatar answered Feb 03 '23 10:02

ApproachingDarknessFish


If you really want boolean[] then populating list and finally converting list into an array shouldn't be necessary. Just do the following:

boolean[] bools = new boolean[o.length()];
for (int i = 0; i < o.length(); i++) {
    bools[i] = Integer.parseInt(o.substring(i,i+1)) == 1;
}

Note: The fact that fool.toArray(new boolean[fool.size()]) doesn't work is because that method is a generic method and in Java generics doesn't work for primitives. It works only for reference types (i.e. objects).

like image 27
Bhesh Gurung Avatar answered Feb 03 '23 10:02

Bhesh Gurung