Reputation: 754
I am trying to construct a boolean[][] from a text file. I am reading in each character, storing in an ArrayList (1s as true and 0s as false). I tried ArrayList, but got compile errors, unexpected element. So, I build an ArrayList, and try to store it in an ArrayList>. My last problem is with the type difference between boolean and Boolean in the following method. seedInProgress is the ArrayList> constructed by finishLine(). I am trying to copy it all out to a boolean[][] inside the for loop.
public void finishSeed(ArrayList<Boolean> lastLine) {
finishLine(lastLine);
seed = new boolean[seedInProgress.size()][seedInProgress.get(0).size()];
for (int i = 0; i < seedInProgress.size(); i++ ) {
seed[i] = seedInProgress.get(i).toArray()
}
}
The error is:
SeedFactory.java:75: error: incompatible types
seed[i] = seedInProgress.get(i).toArray();
^
required: boolean[]
found: Object[]
1 error
but I can't cast it to boolean[], and Boolean[] is still an Object[].
How can I get a boolean[] from an ArrayList, or alternatively, how can I make an ArrayList?
Upvotes: 1
Views: 4858
Reputation: 425083
Java won't autobox whole arrays at a time, if that is what you were hoping. Ie
boolean b;
Boolean B;
a = B; // OK
boolean[] bs;
Boolean[] Bs;
bs = Bs; // compiler error
But really why are you creating a List<Boolean>
first? I would simply pass the line as a String, because it is a String. And your method is a bit too complicated - it does too much and knows about too much.
See if this method helps:
public static boolean[] toBooleanArray(String line) {
boolean[] array = new boolean[line.length()];
for (int i = 0; i < line.length(); i++ )
array[i] = line.charAt(I) == '1';
return array;
}
Your file could be then converted to a List<boolean[]>
like this:
List<boolean[]> lines = new ArrayList<boolean[]>();
// loop reading "line" from file
lines.add(toBooleanArray(line));
then to get a boolean[][]
:
boolean[][] array = lines.toArray();
Upvotes: 1
Reputation: 198163
To get a lowercase boolean[]
from an ArrayList<Boolean>
, you have to do the for
loop yourself, or use a utility method that does the same thing, a la Guava's Booleans.toArray
.
The for
loop is what you'd expect:
boolean[] array = new boolean[list.size()];
for (int i = 0; i < list.size(); i++) {
array[i] = list.get(i);
}
Upvotes: 4