英文:
How to add an object with multiple fields into an ArrayList?
问题
我对Java还不太熟悉,我一直在尝试将一个对象添加到存储相应对象类型的ArrayList中。然而,有一个问题。我希望无限地向ArrayList中添加对象。长度是基于用户输入的,所以我不能预先定义它们,然后在初始化字段后使用 .add() 方法。
这是相关的类。有4个私有字段和公有的getter和setter(只包括两个作为上下文):
public class Player {
private int id; // 每个玩家的ID将是唯一的。
private int roundScore; // 在一轮中累积的分数,如果玩家投掷了一个双数可能会被重置。
private int bankScore; // 玩家的保险分数。
private String name;
public Player() {
roundScore = 0;
bankScore = 0;
}
public void setID(int id) {
this.id = id;
}
public int getID() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
而这是我尝试用来生成玩家的方法(此方法在另一个类中):
public void generatePlayers(int num) {
Player dummyPlayer = new Player();
List<Player> playerList = new ArrayList<Player>();
Scanner sr = new Scanner(System.in);
for (int i = 0; i < num; i++) {
dummyPlayer.setID(i);
System.out.println("\nWhat is the name of player " + i++ + "?");
dummyPlayer.setName(sr.nextLine());
System.out.println(dummyPlayer.getName() + ", welcome to the game!");
playerList.add(dummyPlayer); // 哎呀,这很傻。
}
}
想法是创建一个名为 "dummyPlayer" 的玩家对象实例,将变量存储到对象中,然后将对象添加到ArrayList中。 "应该没问题,对吧?" 至少在我意识到我实际上添加了多个相同对象的实例之前是这样的,如果我更改其中一个对象,它们都会发生变化,因为引用是个问题。
有办法分别设置数组中每个值的字段吗?如果我漏掉了什么重要的东西或者问了一些愚蠢的问题,我很抱歉。我尝试搜索其他问题,但它们没有完全解答我的疑惑。感谢您的时间。
英文:
I'm fairly new to Java and I've been trying to add an object to an ArrayList storing the respective object type. However, there is a catch. I want to have an indefinite amount of objects added into the ArrayList. The length is based on the user input, so I can't define them beforehand and use .add() after initializing the fields.
This is the class in question. There are 4 private fields and public getters and setters (only two included for context):
public class Player {
private int id; // This will be unique for each player.
private int roundScore; // Score accumulated during a round, suspect to be reset if the player rolls a double.
private int bankScore; // Secured score of a player.
private String name;
public Player() {
roundScore = 0;
bankScore = 0;
}
public void setID(int id) {
this.id = id;
}
public int getID() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
And this is the method I tried to use to generate players (this method is in another class):
public void generatePlayers(int num) {
Player dummyPlayer = new Player();
List<Player> playerList = new ArrayList<Player>();
Scanner sr = new Scanner(System.in);
for (int i = 0; i < num; i++) {
dummyPlayer.setID(i);
System.out.println("\nWhat is the name of player " + i++ + "?");
dummyPlayer.setName(sr.nextLine());
System.out.println(dummyPlayer.getName() + ", welcome to the game!");
playerList.add(dummyPlayer); // Oops, this is dumb.
}
}
The idea was to create an instance of a player object called "dummyPlayer", store the variables into the object and add the object into the ArrayList. "Should be fine, right?" or so I thought before I realized I basically added multiple instances of the same object which will all change if I change one of them because referencing is a thing.
Is there a way to individually set the fields of each value in the array? I'm sorry if I missed something vital or asking something stupid. I tried to search other questions but they didn't quite click. Thank you for your time.
答案1
得分: 0
根据 @tgdavies 的评论,将 generatePlayers()
更改为将 new Player()
的部分移动到 for 循环内,代码如下:
public void generatePlayers(int num) {
List<Player> playerList = new ArrayList<Player>();
Scanner sr = new Scanner(System.in);
for (int i = 0; i < num; i++) {
Player dummyPlayer = new Player();
dummyPlayer.setID(i);
System.out.println("\nWhat is the name of player " + i++ + "?");
dummyPlayer.setName(sr.nextLine());
System.out.println(dummyPlayer.getName() + ", welcome to the game!");
playerList.add(dummyPlayer); // 错误,这是愚蠢的。
}
}
这样,对于每次 for 循环的迭代,都会创建一个新的 Player
实例,你可以保留现有的 dummyPlayer
变量(因为局部变量只在其声明的块内存在)。
如果由于某种原因需要在 for 循环外部引用 dummyPlayer
变量,你可以在循环之前仅声明类型和变量名,并在循环内实例化 Player
类:
//... 与上述代码相同
Player dummyPlayer; // 注意可能为 null
for (int i = 0; i < num; i++) {
dummyPlayer = new Player(); // 实例化 Player 类
//... 与上述代码相同
}
dummyPlayer.toString(); // 你仍然可以从这里引用 dummyPlayer
英文:
As commented by @tgdavies, change generatePlayers() to move the new Player()
line inside the for loop like so:
public void generatePlayers(int num) {
List<Player> playerList = new ArrayList<Player>();
Scanner sr = new Scanner(System.in);
for (int i = 0; i < num; i++) {
Player dummyPlayer = new Player();
dummyPlayer.setID(i);
System.out.println("\nWhat is the name of player " + i++ + "?");
dummyPlayer.setName(sr.nextLine());
System.out.println(dummyPlayer.getName() + ", welcome to the game!");
playerList.add(dummyPlayer); // Oops, this is dumb.
}
}
This way for every iteration of the for loop you create a new instance of Player
, and you get to keep the as-is dummyPlayer
variable (since local variables only exist within the block it is stated).
If for some reason there is a need to reference the dummyPlayer
variable outside the for loop, you can state just the type and variable name before the loop and instantiate the Player
class in the loop:
//... Same as above
Player dummyPlayer; //beware of null
for (int i = 0; i < num; i++) {
dummyPlayer = new Player(); //Player class instantiation
//... Same as above
}
dummyPlayer.toString(); //you can still reference dummyPlayer from here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论