Reputation: 595
I am trying to convert a result set with 2 columns into an arraList of arrays. To check my code I then print it out. For that purpose I made a little table compromised of 2 columns á 5 rows.
Problem is that my test print prints out 5 times my original table. So now I'm confused. Is my way of converting the resultSet wrong or am I not printing right? Could somebody help?
Code:
public static void partner() {
ArrayList <int[]> result = new ArrayList<int[]>();
String select = "SELECT ID, age FROM individuen WHERE age BETWEEN 20 AND 40 " +
"AND Familienstand IS 2 ORDER BY RANDOM() LIMIT 5";
DBController dbc = DBController.getInstance();
dbc.initDBConnection();
try {
Statement stmt = DBController.connection.createStatement();
ResultSet rs = stmt.executeQuery(select);
int columnCount = rs.getMetaData().getColumnCount();
while(rs.next()){
int[] row = new int[columnCount];
for (int i = 0; i < columnCount ; i++){
row[i] = rs.getInt(i + 1);
}
result.add(row);
}
Iterator<int[]> it = result.iterator();
while (it.hasNext()) {
for (int[] arr : result) {
System.out.println(Arrays.toString(arr));
}
it.next();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Upvotes: 0
Views: 1115
Reputation: 5366
keep only one loop either for
or while
loop.
for (int[] arr : result) {
System.out.println(Arrays.toString(arr));
}
Upvotes: 3
Reputation: 393771
You have a nested iteration over your ArrayList
, which means you iterate over the ArrayList
multiple times (the number of times being the size()
of the ArrayList
).
You just need a single for loop :
for (int[] arr : result) {
System.out.println(Arrays.toString(arr));
}
or a single while loop :
Iterator<int[]> it = result.iterator();
while (it.hasNext()) {
System.out.println(Arrays.toString(it.next()));
}
not both.
Upvotes: 1