0

I'm working on a project that involves the program interacting with an MySQL database, when the query is run to get a certain amount of values from a database, it executes it and then stores the values as an object, eventually passing them to a list.

At the moment, it gets the information from the database okay, passes the variables through okay, but when I go to print the object in that lists name, it returns all the same values (the last value to be passed through).

How would I go about returning all the object values stored in that list?

The code is below:

ArrayList<Game> gameDetails = new ArrayList<Game>();

while (rs.next()) {

    String gameName = rs.getString("game");
    int score = rs.getInt("score");
    int time = rs.getInt("time");


    gameDetails.add(new Game(gameName, score, time));

    System.out.println(gameName);
}
for (int i = 0; i < gameDetails.size(); i++) {

    System.out.println(gameDetails.get(i).getName());
}

And the Game object class

public class Game {

    private static String name = "";
    private static int time = 0, score = 0;

    public Game(String n, int t, int s) {
        this.name = n;
        this.time = t;
        this.score = s;
    }

    public static String getName() {
        return name;
    }

    public static int getScore() {
        return score;
    }

    public static int getTime() {
        return time;
    }

    public static void setName(String n) {
        name = n;
    }

    public static void setTime(int t) {
        time = t;
    }

    public static void setScore(int s) {
        score = s;
    }
}

At the moment, it returns this value in the console, without the getName() method:

Game@516a3a8
Game@6c9844ae
Game@17115812

And it returns

Call of Duty
Call of Duty
Call of Duty

With the getName() method

So it looks like each value is unique, only not when I go to call the getName() method.

Any help would be hugely appreciated!

Thank you!

2 Answers 2

4

Because you are using static variables to hold the Game values, so EVERY game value uses the same instance of these variables, so EVERY game object will have the same values. Remove static from name, time, and score in Game definition

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

Comments

2

You are using static member variables in Game class. When you declare fields as private static members (instead of private), these fields are shared across all instances of Game object. Hence every time you change the value of the field e.g. name field, value will be updated in the shared reference. Changing the fields to just private should work.

 private String name = "";
 private int time = 0, score = 0;

Comments

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.