简体   繁体   中英

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?

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 boolean s using generics, and autoboxing or casting does not work with arrays (eg 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++.

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 (ie objects).

int index = 0;
boolean[] array = new boolean[fool.size()];
for (Boolean value: fool) {
  array[index++] = value;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM