0

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

1 Answer 1

1

This is because you have declared your edit: attributes in your profile class as static, and as a general rule, static belongs to a class while non-static belongs to an object.

Static methods are useful if you have only one instance where you're going to use the method.

Since you have multiple instances here (object) = this isn't what you want.

Sign up to request clarification or add additional context in comments.

5 Comments

Unfortunately, your suggestion did not work. I made the arraylist non-static, but I still encountered the same issue
@DoubleU difficult to debug without the code for that class. check for static there otherwise edit your answer to show a minimal reproducible example. thanks!
I guess there's a chance too that your SQL query is returning dups. print those values and make sure maybe
Thanks so much!! I had static attributes in the Profile class as well. I made those non-static and it worked. Again, thanks so much!!
@DoubleU I edited my answer - because I was on track but initially incorrect. I believe you could still have the ArrayList itself static, as long as the profile is non-static. Cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.