1 . If trywithresources and finalize() aren't related -meaning trywithresources doesn't call finalize()- what is the purpose of adding the extra code in this exercise?
2. Furthmore, in my code I left the code where the connection is closed.
In the mentor code, they took out this code. I am using that they took it out because the connection element is being closed in the finalize method?
3. Is there a problem if I write the logic to close the connection before calling the super.finalize() ?
My code:
public class Solution {
private Connection connection;
@Override
protected void finalize() throws Throwable{
if (connection != null) connection.close();
super.finalize();
}
public Solution(Connection connection) {
this.connection = connection;
}
public List<User> getUsers() throws Exception {
String query = "select ID, DISPLAYED_NAME, LEVEL, LESSON from USER";
List<User> result = new LinkedList();
try ( Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(query) ){
while (rs.next())
{
int id = rs.getInt("ID");
String name = rs.getString("DISPLAYED_NAME");
int level = rs.getInt("LEVEL");
int lesson = rs.getInt("LESSON");
result.add(new User(id, name, level, lesson));
}
if(stmt != null) stmt.close();
if(rs != null) rs.close();
}
return result;
}
Mentor code:
public class Solution {
private Connection connection;
public Solution(Connection connection) {
this.connection = connection;
}
public List<User> getUsers() {
String query = "select ID, DISPLAYED_NAME, LEVEL, LESSON from USER";
List<User> result = new LinkedList();
try (Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
) {
while (rs.next()) {
int id = rs.getInt("ID");
String name = rs.getString("DISPLAYED_NAME");
int level = rs.getInt("LEVEL");
int lesson = rs.getInt("LESSON");
result.add(new User(id, name, level, lesson));
}
} catch (SQLException e) {
e.printStackTrace();
result = null;
}
return result;
}