如何将一个具有多个字段的对象添加到ArrayList中?

huangapple go评论180阅读模式
英文:

How to add an object with multiple fields into an ArrayList?

问题

  1. 我对Java还不太熟悉我一直在尝试将一个对象添加到存储相应对象类型的ArrayList然而有一个问题我希望无限地向ArrayList中添加对象长度是基于用户输入的所以我不能预先定义它们然后在初始化字段后使用 .add() 方法
  2. 这是相关的类4个私有字段和公有的gettersetter只包括两个作为上下文):
  3. public class Player {
  4. private int id; // 每个玩家的ID将是唯一的。
  5. private int roundScore; // 在一轮中累积的分数,如果玩家投掷了一个双数可能会被重置。
  6. private int bankScore; // 玩家的保险分数。
  7. private String name;
  8. public Player() {
  9. roundScore = 0;
  10. bankScore = 0;
  11. }
  12. public void setID(int id) {
  13. this.id = id;
  14. }
  15. public int getID() {
  16. return id;
  17. }
  18. public String getName() {
  19. return name;
  20. }
  21. public void setName(String name) {
  22. this.name = name;
  23. }
  24. 而这是我尝试用来生成玩家的方法此方法在另一个类中):
  25. public void generatePlayers(int num) {
  26. Player dummyPlayer = new Player();
  27. List<Player> playerList = new ArrayList<Player>();
  28. Scanner sr = new Scanner(System.in);
  29. for (int i = 0; i < num; i++) {
  30. dummyPlayer.setID(i);
  31. System.out.println("\nWhat is the name of player " + i++ + "?");
  32. dummyPlayer.setName(sr.nextLine());
  33. System.out.println(dummyPlayer.getName() + ", welcome to the game!");
  34. playerList.add(dummyPlayer); // 哎呀,这很傻。
  35. }
  36. }
  37. 想法是创建一个名为 "dummyPlayer" 的玩家对象实例将变量存储到对象中然后将对象添加到ArrayList "应该没问题,对吧?" 至少在我意识到我实际上添加了多个相同对象的实例之前是这样的如果我更改其中一个对象它们都会发生变化因为引用是个问题
  38. 有办法分别设置数组中每个值的字段吗如果我漏掉了什么重要的东西或者问了一些愚蠢的问题我很抱歉我尝试搜索其他问题但它们没有完全解答我的疑惑感谢您的时间
英文:

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):

  1. public class Player {
  2. private int id; // This will be unique for each player.
  3. private int roundScore; // Score accumulated during a round, suspect to be reset if the player rolls a double.
  4. private int bankScore; // Secured score of a player.
  5. private String name;
  6. public Player() {
  7. roundScore = 0;
  8. bankScore = 0;
  9. }
  10. public void setID(int id) {
  11. this.id = id;
  12. }
  13. public int getID() {
  14. return id;
  15. }
  16. public String getName() {
  17. return name;
  18. }
  19. public void setName(String name) {
  20. this.name = name;
  21. }

And this is the method I tried to use to generate players (this method is in another class):

  1. public void generatePlayers(int num) {
  2. Player dummyPlayer = new Player();
  3. List&lt;Player&gt; playerList = new ArrayList&lt;Player&gt;();
  4. Scanner sr = new Scanner(System.in);
  5. for (int i = 0; i &lt; num; i++) {
  6. dummyPlayer.setID(i);
  7. System.out.println(&quot;\nWhat is the name of player &quot; + i++ + &quot;?&quot;);
  8. dummyPlayer.setName(sr.nextLine());
  9. System.out.println(dummyPlayer.getName() + &quot;, welcome to the game!&quot;);
  10. playerList.add(dummyPlayer); // Oops, this is dumb.
  11. }
  12. }

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 循环内,代码如下:

  1. public void generatePlayers(int num) {
  2. List<Player> playerList = new ArrayList<Player>();
  3. Scanner sr = new Scanner(System.in);
  4. for (int i = 0; i < num; i++) {
  5. Player dummyPlayer = new Player();
  6. dummyPlayer.setID(i);
  7. System.out.println("\nWhat is the name of player " + i++ + "?");
  8. dummyPlayer.setName(sr.nextLine());
  9. System.out.println(dummyPlayer.getName() + ", welcome to the game!");
  10. playerList.add(dummyPlayer); // 错误,这是愚蠢的。
  11. }
  12. }

这样,对于每次 for 循环的迭代,都会创建一个新的 Player 实例,你可以保留现有的 dummyPlayer 变量(因为局部变量只在其声明的块内存在)。

如果由于某种原因需要在 for 循环外部引用 dummyPlayer 变量,你可以在循环之前仅声明类型和变量名,并在循环内实例化 Player 类:

  1. //... 与上述代码相同
  2. Player dummyPlayer; // 注意可能为 null
  3. for (int i = 0; i < num; i++) {
  4. dummyPlayer = new Player(); // 实例化 Player 类
  5. //... 与上述代码相同
  6. }
  7. dummyPlayer.toString(); // 你仍然可以从这里引用 dummyPlayer
英文:

As commented by @tgdavies, change generatePlayers() to move the new Player() line inside the for loop like so:

  1. public void generatePlayers(int num) {
  2. List&lt;Player&gt; playerList = new ArrayList&lt;Player&gt;();
  3. Scanner sr = new Scanner(System.in);
  4. for (int i = 0; i &lt; num; i++) {
  5. Player dummyPlayer = new Player();
  6. dummyPlayer.setID(i);
  7. System.out.println(&quot;\nWhat is the name of player &quot; + i++ + &quot;?&quot;);
  8. dummyPlayer.setName(sr.nextLine());
  9. System.out.println(dummyPlayer.getName() + &quot;, welcome to the game!&quot;);
  10. playerList.add(dummyPlayer); // Oops, this is dumb.
  11. }
  12. }

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:

  1. //... Same as above
  2. Player dummyPlayer; //beware of null
  3. for (int i = 0; i &lt; num; i++) {
  4. dummyPlayer = new Player(); //Player class instantiation
  5. //... Same as above
  6. }
  7. dummyPlayer.toString(); //you can still reference dummyPlayer from here

huangapple
  • 本文由 发表于 2020年10月14日 13:47:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/64347327.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定