Reputation: 1909
I have a problem with the code below. Compiler says incompatible types, java.lang.object[][] required but found java.lang.object[].
Anyone have an idea why this is? I've found some about generics that gives problems here but no solution to my problem.
Object sqlQuery[][] = null;
List<Object[]> sqlLista = new ArrayList<Object[]>();
while (resultSet.next()) {
sqlLista.add(new Object[] { false, resultSet.getString("MMITNO"), null, null, null, null, null } );
}
sqlQuery = sqlLista.toArray();
edit: I have edited the code above as i see i had made a mistake with the dimensions
Upvotes: 1
Views: 2287
Reputation: 9505
sqlLista.toArray();
returns array where each element = Object[][], the return array's type is not Object[][] itself.
Change your code onto:
Object sqlQuery[][] = new Object[][] { };
List<Object[]> sqlLista = new ArrayList<Object[]>();
while (resultSet.next()) {
sqlLista.add(new Object[] { false, resultSet.getString("MMITNO"), null, null, null, null, null } );
}
sqlQuery = sqlLista.toArray();
Upvotes: 3
Reputation: 8245
Look at the declaration of List.toArray().
It wants to convert to an array of Object (Object[]).
But sqlQuery
is declared as an array of an array of Object (Object[][]).
What to do from here depends on what you want to achieve with your code. You may want to create a specific class for a row, and create a List of instances of that class, instead of an array of Object[][].
Upvotes: 0
Reputation: 1500225
The problem is that you're calling the parameterless overload of toArray()
, which returns Object[]
. You can't assign an Object[]
to an Object[][]
variable.
Now it seems to me that you possibly actually want to make sqlQuery
an Object[][][]
instead of an Object[][]
, so that you get one two-dimensional array per entry in the result set. You'd then have:
// Please use this form rather than putting the brackets after the name
// - it keeps all the type information together.
Object[][][] sqlQuery = null; // No point giving it a dummy value
List<Object[][]> list = new ArrayList<Object[][]>();
...
sqlQuery = list.toArray(new Object[0][][]);
However, I'd strongly advise you not to go down this route anyway - encapsulate the "result" concept which is currently just Object[][]
in a new type, so you'd have:
Result[] sqlQuery = null;
List<Result> list = new ArrayList<Result>();
...
sqlQuery = list.toArray(new Result[0]);
This will be a lot easier to reason about - even if Result
only contains an Object[][]
.
Upvotes: 3