I am working on a project where I loop through a database and add "Profile" objects to an arraylist (searchResults), but for some reason, the last object created from looping through the resultset is duplicated across the arraylist. Please see code snippet below:
public static ArrayList<Profile> searchResults;
public void showSearchResults(){
searchResults = new ArrayList<>();
searchResults.clear();
try {
// create SQL statement object for query
statement = Connect.toDatabase();
resultSet = statement.executeQuery (SQL query here)
while(resultSet.next()){
Profile newProfile = new Profile();
newProfile.setUsername(resultSet.getString("username"));
newProfile.setFirstName(resultSet.getString("first_name"));
newProfile.setLastName(resultSet.getString("last_name"));
newProfile.setGender(resultSet.getString("gender"));
newProfile.setAge(String.valueOf(resultSet.getInt("age")));
newProfile.setCity(resultSet.getString("city"));
searchResults.add(newProfile);
}
} catch (SQLException e) {
// print out exceptions
e.printStackTrace();
} finally {
// close the connections
Connect.closeConnection(statement, resultSet);
showResults = true;
}
}
public ArrayList<Profile> getSearchResults() {
return searchResults;
}
Any help with this issue would be greatly appreciated. Thanks in advance